MCPcopy Create free account
hub / github.com/davisking/dlib / hostname_to_ip

Function hostname_to_ip

dlib/sockets/sockets_kernel_1.cpp:128–184  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

126// -----------------
127
128 int
129 hostname_to_ip (
130 const std::string& hostname,
131 std::string& ip,
132 int n
133 )
134 {
135 // ensure that WSAStartup has been called and WSACleanup will eventually
136 // be called when program ends
137 sockets_startup();
138
139 try
140 {
141 // lock this mutex since gethostbyname isn't really thread safe
142 auto_mutex M(sockets_kernel_1_mutex::startup_lock);
143
144 // if no hostname was given then return error
145 if ( hostname.empty())
146 return OTHER_ERROR;
147
148 hostent* address;
149 address = gethostbyname(hostname.c_str());
150
151 if (address == 0)
152 {
153 return OTHER_ERROR;
154 }
155
156 // find the nth address
157 in_addr* addr = reinterpret_cast<in_addr*>(address->h_addr_list[0]);
158 for (int i = 1; i <= n; ++i)
159 {
160 addr = reinterpret_cast<in_addr*>(address->h_addr_list[i]);
161
162 // if there is no nth address then return error
163 if (addr == 0)
164 return OTHER_ERROR;
165 }
166
167 char* resolved_ip = inet_ntoa(*addr);
168
169 // check if inet_ntoa returned an error
170 if (resolved_ip == NULL)
171 {
172 return OTHER_ERROR;
173 }
174
175 ip.assign(resolved_ip);
176
177 }
178 catch(...)
179 {
180 return OTHER_ERROR;
181 }
182
183 return 0;
184 }
185

Callers

nothing calls this directly

Calls 3

sockets_startupFunction · 0.70
emptyMethod · 0.45
assignMethod · 0.45

Tested by

no test coverage detected