IP address from host name in windows socket programming

12,279

Solution 1

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.

Solution 2

#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 {};
}

Solution 3

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).

Share:
12,279
Neel Patel
Author by

Neel Patel

Updated on June 07, 2022

Comments

  • Neel Patel
    Neel Patel almost 2 years

    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?