Getting IP Address Of Host

From WxWiki
Jump to navigation Jump to search

Getting the IP address of a host

The easiest way appears to be: gethostbyname(wxGetFullHostName())

See also:


gethostbyname() can and should return _all_ the IP addresses bound to that name, in _no_ defined order so you might have to check that you haven't got as the first address and use the second address in the list instead in that case. (quoted Roger Gammans)

In practice, however, it appears that only is returned: "hostname" is an alias for "localhost" in those cases, _not_ for "hostname.domainname". Using gethostname _and_ getdomainname and concatenating them before calling gethostbyname might help, though. (quoted Stefan)

A Better Method

A more wxWidgets (and hopefully more portable) method is to do:

 wxIPV4address addr;
 wxString ipAddr = addr.IPAddress();

Public IP address

To get your public/external IP address make a client connection with a remote Internet host and then get the local address information from the socket. You incur overhead from creating a TCP connection, if you can, use an existing socket in your Internet application to get your local address. If the host is behind NAT the IP address returned will be the host's private LAN IP address, or whichever address is used to forward to the default gateway.

 wxIPV4address remote;
 wxIPV4address local;
 wxSocketClient client;
 if(client.Connect(remote)) client.GetLocal(local);
 wxString ipAddr=local.IPAddress();

Enumerating Interfaces

Getting the IP address of one's host is really a special case of the more general problem of enumerating all network interfaces on a host.

Microsoft Windows offers the GetAdapterInfo API for listing information about interfaces.

In Linux, one uses the SIOCGIFCONF ioctl on an INET DGRAM socket to list interface information. A code example can be found here.