
SOCKADDR_IN6* ipv6 = reinterpret_cast(address->Address.lpSockaddr) Inet_ntop(AF_INET, &(ipv4->sin_addr), str_buffer, INET_ADDRSTRLEN) SOCKADDR_IN* ipv4 = reinterpret_cast(address->Address.lpSockaddr) IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress Īuto family = address->Address.lpSockaddr->sa_family

If (IF_TYPE_SOFTWARE_LOOPBACK = adapter->IfType) we are in the middle of querying them.ĭWORD adapter_addresses_buffer_size = 16 * KB įor (int attempts = 0 attempts != 3 ++attempts)Īdapter_addresses = (IP_ADAPTER_ADDRESSES*)malloc(adapter_addresses_buffer_size) įor (adapter = adapter_addresses NULL != adapter adapter = adapter->Next) multiple attempts in case interfaces change while Start with a 16 KB buffer and resize if needed.

IP_ADAPTER_ADDRESSES* adapter_addresses(NULL) Here is an example of how you can iterate through all Ipv4 and Ipv6 addresses on the host machine: void ListIpAddresses(IpAddresses& ipAddrs) Servers usually have more than one adapter. The problem with all the approaches based on gethostbyname is that you will not get all IP addresses assigned to a particular machine. For example usages of both, see the GetNetworkInterfaceInfos() function in this file. Under Windows, try GetAdaptersAddresses() to get similar functionality. The best way to do that under Unix/Mac (AFAIK) is by calling getifaddrs() and iterating over the results. when you're not communicating with a particular computer) so sometimes you just need to gather the list of all the IP addresses associated with your machine. That said, that trick may not be appropriate for some purposes (e.g. That way you will know what the relevant IP address is, given the context of the computer you are communicating with. if you are writing a client program, send a message to the server asking the server to send back as data the IP address that your request came from. In my experience often the best way to get "an IP address" for your local computer is not to query the local computer at all, but rather to ask the computer your program is talking to what it sees your computer's IP address as.

they are all "real" and useful some more useful than others depending on what you are going to use the addresses for. and it's not just a matter of figuring out which of the above is "the real IP address", either. For example, the Mac I'm typing on right now (which is a pretty basic, standard Mac setup) has the following IP addresses associated with it: fe80::1%lo0 The question is trickier than it appears, because in many cases there isn't "an IP address for the local computer" so much as a number of different IP addresses.
