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