b0da748ff0f18616f956df3438836b1410d30444
1 /* gethostname emulation for SysV and POSIX.1.
3 Copyright (C) 1992, 2003, 2006, 2008, 2009, 2010 Free Software Foundation,
4 Inc.
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 /* David MacKenzie <djm@gnu.ai.mit.edu>
20 Windows port by Simon Josefsson <simon@josefsson.org> */
22 #include <config.h>
24 #if !((defined _WIN32 || defined __WIN32__) && !defined __CYGWIN__)
25 /* Unix API. */
27 /* Specification. */
28 #include <unistd.h>
30 #ifdef HAVE_UNAME
31 # include <sys/utsname.h>
32 #endif
34 #include <string.h>
36 /* Put up to LEN chars of the host name into NAME.
37 Null terminate it if the name is shorter than LEN.
38 Return 0 if ok, -1 if error. */
40 #include <stddef.h>
42 int
43 gethostname (char *name, size_t len)
44 {
45 #ifdef HAVE_UNAME
46 struct utsname uts;
48 if (uname (&uts) == -1)
49 return -1;
50 if (len > sizeof (uts.nodename))
51 {
52 /* More space than we need is available. */
53 name[sizeof (uts.nodename)] = '\0';
54 len = sizeof (uts.nodename);
55 }
56 strncpy (name, uts.nodename, len);
57 #else
58 strcpy (name, ""); /* Hardcode your system name if you want. */
59 #endif
60 return 0;
61 }
63 #else
64 /* Native Windows API. Which primitive to choose?
65 - gethostname() requires linking with -lws2_32.
66 - GetComputerName() does not return the right kind of hostname.
67 - GetComputerNameEx(ComputerNameDnsHostname,...) returns the right hostname,
68 but it is hard to use portably:
69 - It requires defining _WIN32_WINNT to at least 0x0500.
70 - With mingw, it also requires
71 "#define GetComputerNameEx GetComputerNameExA".
72 - With older versions of mingw, none of the declarations are present at
73 all, not even of the enum value ComputerNameDnsHostname.
74 So we use gethostname(). Linking with -lws2_32 is the least evil. */
76 #define WIN32_LEAN_AND_MEAN
77 /* Get winsock2.h. */
78 #include <unistd.h>
80 /* Get INT_MAX. */
81 #include <limits.h>
83 /* Get set_winsock_errno. */
84 #include "w32sock.h"
86 #include "sockets.h"
88 #undef gethostname
90 int
91 rpl_gethostname (char *name, size_t len)
92 {
93 int r;
95 if (len > INT_MAX)
96 len = INT_MAX;
97 gl_sockets_startup (SOCKETS_1_1);
98 r = gethostname (name, (int) len);
99 if (r < 0)
100 set_winsock_errno ();
102 return r;
103 }
105 #endif