check_snmp: Remove unused PP-macros
[monitoring-plugins.git] / gl / gethostname.c
blob0c616c346fd96cf3f4392a9c42edaec65632a4f5
1 /* gethostname emulation for SysV and POSIX.1.
3 Copyright (C) 1992, 2003, 2006, 2008-2023 Free Software Foundation, Inc.
5 This file is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as
7 published by the Free Software Foundation; either version 2.1 of the
8 License, or (at your option) any later version.
10 This file 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 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 /* David MacKenzie <djm@gnu.ai.mit.edu>
19 Windows port by Simon Josefsson <simon@josefsson.org> */
21 #include <config.h>
23 #if !(defined _WIN32 && !defined __CYGWIN__)
24 /* Unix API. */
26 /* Specification. */
27 #include <unistd.h>
29 #ifdef HAVE_UNAME
30 # include <sys/utsname.h>
31 #endif
33 #include <string.h>
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. */
39 #include <stddef.h>
41 int
42 gethostname (char *name, size_t len)
44 #ifdef HAVE_UNAME
45 struct utsname uts;
47 if (uname (&uts) == -1)
48 return -1;
49 if (len > sizeof (uts.nodename))
51 /* More space than we need is available. */
52 name[sizeof (uts.nodename)] = '\0';
53 len = sizeof (uts.nodename);
55 strncpy (name, uts.nodename, len);
56 #else
57 strcpy (name, ""); /* Hardcode your system name if you want. */
58 #endif
59 return 0;
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. */
75 #define WIN32_LEAN_AND_MEAN
76 /* Get winsock2.h. */
77 #include <unistd.h>
79 /* Get INT_MAX. */
80 #include <limits.h>
82 /* Get set_winsock_errno. */
83 #include "w32sock.h"
85 #include "sockets.h"
87 #undef gethostname
89 int
90 rpl_gethostname (char *name, size_t len)
92 int r;
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 ();
101 return r;
104 #endif