2f9a261e8dc2fe3bc97c772a29b9faf1d23e6e6f
[uffi.git] / examples / gethostname.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          gethostname.cl
6 ;;;; Purpose:       UFFI Example file to get hostname of system
7 ;;;; Programmer:    Kevin M. Rosenberg
8 ;;;; Date Started:  Feb 2002
9 ;;;;
10 ;;;; $Id$
11 ;;;;
12 ;;;; This file, part of UFFI, is Copyright (c) 2002 by Kevin M. Rosenberg
13 ;;;;
14 ;;;; UFFI users are granted the rights to distribute and use this software
15 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
16 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
17 ;;;; *************************************************************************
18
19 (in-package :cl-user)
20
21
22 ;;; This example is inspired by the example on the CL-Cookbook web site
23
24 (uffi:def-function ("gethostname" c-gethostname) 
25     ((name (* :unsigned-char))
26      (len :int))
27   :returning :int)
28
29 (defun gethostname ()
30   "Returns the hostname"
31   (let* ((name (uffi:allocate-foreign-string 256))
32          (result-code (c-gethostname name 256))
33          (hostname (when (zerop result-code)
34                      (uffi:convert-from-foreign-string name))))
35     (uffi:free-foreign-object name)
36     (unless (zerop result-code)
37       (error "gethostname() failed."))
38     hostname))
39
40 (defun gethostname2 ()
41   "Returns the hostname"
42   (uffi:with-foreign-object (name '(:array :unsigned-char 256))
43     (if (zerop (c-gethostname (uffi:char-array-to-pointer name) 256))
44         (uffi:convert-from-foreign-string name)
45         (error "gethostname() failed."))))
46
47 #+examples-uffi
48 (progn
49   (format t "~&Hostname (technique 1): ~A" (gethostname))
50   (format t "~&Hostname (technique 2): ~A" (gethostname2)))
51
52 #+test-uffi
53 (progn
54   (let ((hostname1 (gethostname))
55         (hostname2 (gethostname2)))
56     
57     (util.test:test (and (stringp hostname1) (stringp hostname2)) t
58                     :fail-info "gethostname not string")
59     (util.test:test (and (not (zerop (length hostname1)))
60                          (not (zerop (length hostname2)))) t
61                          :fail-info "gethostname length 0")
62     (util.test:test (string= hostname1 hostname1) t
63                     :fail-info "gethostname techniques don't match"))
64   )
65
66