Reputation: 315
I want to convert host name (computer name My Computer ->property -> Advance System Setting ->computer Name) to IP Address.
Is there any way can I convert host name to IP address? I have tried following but pHostInfo coming as NULL. and hostname is my computer name.
struct hostent* pHostInfo;
pHostInfo = gethostbyname(hostname);
In above code it is coming as NULL. Can you please give me code that convert host name to IP address?
Upvotes: 3
Views: 16326
Reputation: 821
#include <string>
#include <netdb.h>
#include <arpa/inet.h>
std::string HostToIp(const std::string& host) {
hostent* hostname = gethostbyname(host.c_str());
if(hostname)
return std::string(inet_ntoa(**(in_addr**)hostname->h_addr_list));
return {};
}
Upvotes: 5
Reputation: 598001
Use gethostname()
to get the local hostname. You can then pass that to gethostbyname()
.
Note, however, that gethostbyname()
performs a DNS lookup EVEN FOR LOCAL HOSTNAMES, so it is possible to get IP addresses that do not actually belong to the local machine, or invalid IPs if DNS is misconfigured.
If all you really want to do is get the local machine's IP addresses, then use GetAdaptersInfo()
or GetAdaptersAddresses()
instead.
Upvotes: 3
Reputation: 7744
Check getaddrinfo
function! If you are looking for an IPv6 address on Windows XP SP2 (or better), you should use GetAddrInfoW
function. Both of the functions have example in the documentation. If you are working with IPv4 and/or MS Vista and better, you should choose getaddrinfo
because it is platform independent (POSIX.1-2001).
Upvotes: 3