Remove old CVS $Id$ keyword
[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 ;;;; This file, part of UFFI, is Copyright (c) 2002-2010 by Kevin M. Rosenberg
11 ;;;;
12 ;;;; *************************************************************************
13
14 (in-package :cl-user)
15
16
17 ;;; This example is inspired by the example on the CL-Cookbook web site
18
19 (uffi:def-function ("gethostname" c-gethostname)
20     ((name (* :unsigned-char))
21      (len :int))
22   :returning :int)
23
24 (defun gethostname ()
25   "Returns the hostname"
26   (let* ((name (uffi:allocate-foreign-string 256))
27          (result-code (c-gethostname name 256))
28          (hostname (when (zerop result-code)
29                      (uffi:convert-from-foreign-string name))))
30     (uffi:free-foreign-object name)
31     (unless (zerop result-code)
32       (error "gethostname() failed."))
33     hostname))
34
35 (defun gethostname2 ()
36   "Returns the hostname"
37   (uffi:with-foreign-object (name '(:array :unsigned-char 256))
38     (if (zerop (c-gethostname (uffi:char-array-to-pointer name) 256))
39         (uffi:convert-from-foreign-string name)
40         (error "gethostname() failed."))))
41
42 #+examples-uffi
43 (progn
44   (format t "~&Hostname (technique 1): ~A" (gethostname))
45   (format t "~&Hostname (technique 2): ~A" (gethostname2)))
46
47 #+test-uffi
48 (progn
49   (let ((hostname1 (gethostname))
50         (hostname2 (gethostname2)))
51
52     (util.test:test (and (stringp hostname1) (stringp hostname2)) t
53                     :fail-info "gethostname not string")
54     (util.test:test (and (not (zerop (length hostname1)))
55                          (not (zerop (length hostname2)))) t
56                          :fail-info "gethostname length 0")
57     (util.test:test (string= hostname1 hostname1) t
58                     :fail-info "gethostname techniques don't match"))
59   )
60
61