MCPcopy Create free account
hub / github.com/WaykiChain/WaykiChain / GetMyPublicIP

Function GetMyPublicIP

src/net.cpp:284–344  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

282}
283
284bool GetMyPublicIP(CNetAddr& ipRet) {
285 ipHost = SysCfg().GetArg("-ipserver", "");
286 if (ipHost == "") {
287 if (SysCfg().NetworkID() == MAIN_NET)
288 ipHost = "wiccip.me";
289 else if (SysCfg().NetworkID() == TEST_NET)
290 ipHost = "wiccip.com";
291 else
292 return true; // no need for RegTest network
293 }
294
295 if (ipHost.find("/") != std::string::npos) {
296 string host = ipHost;
297 ipHost = "";
298 return ERRORMSG("ipserver (%s) contains /", host);
299 }
300
301 CService addrConnect(ipHost, 80, true);
302 if (!addrConnect.IsValid())
303 return ERRORMSG("service is unavalable: %s\n", ipHost);
304
305 stringstream stream;
306 stream << "GET" << " " << "/ip" << " " << "HTTP/1.1\r\n";
307 stream << "Host: " << ipHost << "\r\n";
308 stream << "Connection: close\r\n\r\n";
309 stream << "";
310 string request = stream.str();
311
312 SOCKET hSocket;
313 if (!ConnectSocket(addrConnect, hSocket))
314 return ERRORMSG("failed to connect IP server: %s", addrConnect.ToString());
315
316 send(hSocket, request.c_str(), request.length(), MSG_NOSIGNAL);
317
318 char buffer[ 1024] = {'\0'};
319 recv(hSocket, buffer , 1024, MSG_NOSIGNAL);
320
321 closesocket(hSocket);
322
323 if (strlen(buffer) == 0)
324 return ERRORMSG("failed to receive data from server: %s", addrConnect.ToString());
325
326 static const char* const key = "\"ipAddress\":\"";
327 char* from = strstr(buffer, key);
328 if (from == nullptr) {
329 return ERRORMSG("invalid message");
330 }
331 from += strlen(key);
332 char* to = strstr(from, "\"");
333 string ip(from, to);
334 publicIp = ip;
335 CService ipAddr(publicIp, 0, true);
336 if (!ipAddr.IsValid() /* || !ipAddr.IsRoutable() */)
337 return ERRORMSG("invalid public IP: %s", publicIp);
338
339 ipRet.SetIP(ipAddr);
340
341 LogPrint(BCLog::INFO, "My Public IP is: %s\n", publicIp);

Callers 1

ThreadGetMyPublicIPFunction · 0.85

Calls 9

ConnectSocketFunction · 0.85
GetArgMethod · 0.80
strMethod · 0.80
SetIPMethod · 0.80
NetworkIDMethod · 0.45
findMethod · 0.45
IsValidMethod · 0.45
ToStringMethod · 0.45
lengthMethod · 0.45

Tested by

no test coverage detected