1 /* @(#)gethostname.c	1.23 19/09/01 Copyright 1995-2019 J. Schilling */
2 #include <schily/mconfig.h>
3 #ifndef lint
4 static	UConst char sccsid[] =
5 	"@(#)gethostname.c	1.23 19/09/01 Copyright 1995-2019 J. Schilling";
6 #endif
7 /*
8  *	Copyright (c) 1995-2019 J. Schilling
9  */
10 /*
11  * The contents of this file are subject to the terms of the
12  * Common Development and Distribution License, Version 1.0 only
13  * (the "License").  You may not use this file except in compliance
14  * with the License.
15  *
16  * See the file CDDL.Schily.txt in this distribution for details.
17  * A copy of the CDDL is also available via the Internet at
18  * http://www.opensource.org/licenses/cddl1.txt
19  *
20  * When distributing Covered Code, include this CDDL HEADER in each
21  * file and include the License file CDDL.Schily.txt from this distribution.
22  */
23 
24 #include <schily/standard.h>
25 #include <schily/stdlib.h>
26 #include <schily/systeminfo.h>
27 #include <schily/hostname.h>
28 
29 #ifndef	HAVE_GETHOSTNAME
30 EXPORT	int	gethostname	__PR((char *name, int namelen));
31 
32 
33 #ifdef	SI_HOSTNAME
34 
35 EXPORT int
gethostname(name,namelen)36 gethostname(name, namelen)
37 	char	*name;
38 	int	namelen;
39 {
40 	if (sysinfo(SI_HOSTNAME, name, namelen) < 0)
41 		return (-1);
42 	return (0);
43 }
44 #else	/* ! SI_HOSTNAME */
45 
46 #ifdef	HAVE_UNAME
47 #include <schily/utsname.h>
48 #include <schily/string.h>
49 
50 EXPORT int
gethostname(name,namelen)51 gethostname(name, namelen)
52 	char	*name;
53 	int	namelen;
54 {
55 	struct utsname	uts;
56 
57 	if (uname(&uts) < 0)
58 		return (-1);
59 
60 	strncpy(name, uts.nodename, namelen);
61 	return (0);
62 }
63 #else	/* !HAVE_UNAME */
64 
65 #if	defined(__MINGW32__) || defined(_MSC_VER)
66 #include <schily/utypes.h>
67 #include <schily/errno.h>
68 #define	gethostname	__winsock_gethostname
69 #include <schily/windows.h>
70 #undef	gethostname
71 
72 EXPORT int
gethostname(name,namelen)73 gethostname(name, namelen)
74 	char	*name;
75 	int	namelen;
76 {
77 	UInt32_t	len = namelen;
78 	char		nbuf[MAX_COMPUTERNAME_LENGTH+1];
79 
80 	if (namelen < 0) {
81 		seterrno(EINVAL);
82 		return (-1);
83 	}
84 	if (namelen == 0)
85 		return (0);
86 
87 	name[0] = '\0';
88 	if (!GetComputerName(name, &len)) {
89 		if (len > namelen) {
90 			nbuf[0] = '\0';
91 			len = sizeof (nbuf);
92 			(void) GetComputerName(nbuf, &len);
93 			strncpy(name, nbuf, namelen);
94 			return (0);
95 		}
96 		seterrno(EIO);
97 		return (-1);
98 	}
99 	return (0);
100 }
101 #else
102 #include <schily/errno.h>
103 
104 EXPORT int
gethostname(name,namelen)105 gethostname(name, namelen)
106 	char	*name;
107 	int	namelen;
108 {
109 	if (namelen < 0) {
110 		seterrno(EINVAL);
111 		return (-1);
112 	}
113 	if (namelen > 0)
114 		name[0] = '\0';
115 	return (0);
116 }
117 #endif
118 #endif	/* !HAVE_UNAME */
119 
120 #endif	/* !SI_HOSTNAME */
121 
122 #endif	/* HAVE_GETHOSTNAME */
123