Implement gethostname correctly for native Windows.
[gnulib.git] / lib / gethostname.c
1 /* gethostname emulation for SysV and POSIX.1.
2
3    Copyright (C) 1992, 2003, 2006, 2008, 2009 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 <http://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 __WIN32__) && !defined __CYGWIN__)
24
25 /* Specification.  */
26 #include <unistd.h>
27
28 #ifdef HAVE_UNAME
29 # include <sys/utsname.h>
30 #endif
31
32 #include <string.h>
33
34 /* Put up to LEN chars of the host name into NAME.
35    Null terminate it if the name is shorter than LEN.
36    Return 0 if ok, -1 if error.  */
37
38 #include <stddef.h>
39
40 int
41 gethostname (char *name, size_t len)
42 {
43 #ifdef HAVE_UNAME
44   struct utsname uts;
45
46   if (uname (&uts) == -1)
47     return -1;
48   if (len > sizeof (uts.nodename))
49     {
50       /* More space than we need is available.  */
51       name[sizeof (uts.nodename)] = '\0';
52       len = sizeof (uts.nodename);
53     }
54   strncpy (name, uts.nodename, len);
55 #else
56   strcpy (name, "");            /* Hardcode your system name if you want.  */
57 #endif
58   return 0;
59 }
60
61 #else
62
63 #define WIN32_LEAN_AND_MEAN
64 /* Get winsock2.h. */
65 #include <unistd.h>
66
67 /* Get set_winsock_errno. */
68 #include "w32sock.h"
69
70 #undef gethostname
71
72 int
73 rpl_gethostname (char *name, size_t namelen)
74 {
75   int r = gethostname (name, (int) namelen);
76   if (r < 0)
77     set_winsock_errno ();
78
79   return r;
80 }
81
82 #endif