This source file includes following definitions.
- sethostname
- sethostname
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 #include <config.h>
21
22 #if !(defined _WIN32 || defined __CYGWIN__)
23
24
25
26 # include <unistd.h>
27
28 # include <errno.h>
29 # include <stdio.h>
30 # include <limits.h>
31
32
33
34
35 int
36 sethostname (const char *name, size_t len)
37 {
38
39
40 if (len > HOST_NAME_MAX)
41 {
42 errno = EINVAL;
43 return -1;
44 }
45
46 # ifdef __minix
47 {
48 FILE *hostf;
49 int r = 0;
50
51
52
53
54
55 hostf = fopen ("/etc/hostname.file", "we");
56 if (hostf == NULL)
57 r = -1;
58 else
59 {
60 fprintf (hostf, "%.*s\n", (int) len, name);
61 if (ferror (hostf))
62 {
63
64 int saved_errno = errno;
65 fclose (hostf);
66 errno = saved_errno;
67 r = -1;
68 }
69 else
70 {
71 if (fclose (hostf))
72
73 r = -1;
74 }
75 }
76
77 return r;
78 }
79 # else
80
81
82 errno = ENOSYS;
83 return -1;
84 # endif
85 }
86
87 #else
88
89
90
91 # if !defined _WIN32_WINNT || (_WIN32_WINNT < _WIN32_WINNT_WIN2K)
92 # undef _WIN32_WINNT
93 # define _WIN32_WINNT _WIN32_WINNT_WIN2K
94 # endif
95
96 # define WIN32_LEAN_AND_MEAN
97
98
99 # include <unistd.h>
100
101 # include <errno.h>
102 # include <limits.h>
103 # include <string.h>
104
105 # include <windows.h>
106
107
108 # undef GetComputerNameEx
109 # define GetComputerNameEx GetComputerNameExA
110 # undef SetComputerNameEx
111 # define SetComputerNameEx SetComputerNameExA
112
113
114
115
116 int
117 sethostname (const char *name, size_t len)
118 {
119 char name_asciz[HOST_NAME_MAX + 1];
120 char old_name[HOST_NAME_MAX + 1];
121 DWORD old_name_len;
122
123
124
125 if (len > HOST_NAME_MAX)
126 {
127 errno = EINVAL;
128 return -1;
129 }
130
131
132 memcpy (name_asciz, name, len);
133 name_asciz[len] = '\0';
134
135
136 old_name_len = sizeof (old_name) - 1;
137 if (! GetComputerNameEx (ComputerNamePhysicalNetBIOS,
138 old_name, &old_name_len))
139 old_name_len = 0;
140
141
142 if (! SetComputerNameEx (ComputerNamePhysicalNetBIOS, name_asciz))
143 {
144 errno = (GetLastError () == ERROR_ACCESS_DENIED ? EPERM : EINVAL);
145 return -1;
146 }
147 if (! SetComputerNameEx (ComputerNamePhysicalDnsHostname, name_asciz))
148 {
149 errno = (GetLastError () == ERROR_ACCESS_DENIED ? EPERM : EINVAL);
150
151 if (old_name_len > 0)
152 {
153 old_name[old_name_len] = '\0';
154 SetComputerNameEx (ComputerNamePhysicalNetBIOS, old_name);
155 }
156 return -1;
157 }
158
159
160 return 0;
161 }
162
163 #endif