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