<p>In C++, what's the easiest way to get the local computer's IP address and subnet mask?</p>
<p>I want to be able to detect the local machine's IP address in my local network. In my particular case, I have a network with a subnet mask of 255.255.255.0 and my computer's IP address is 192.168.0.5. I need to get these had two values programmatically in order to send a broadcast message to my network (in the form 192.168.0.255, for my particular case)</p>
<p>Edit: Many answers were not giving the results I expected because I had two different network IP's. <a href="https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer#122235">Torial</a>'s code did the trick (it gave me both IP addresses).</p>
<p>Edit 2: Thanks to <a href="https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer#122225">Brian R. Bondy</a> for the info about the subnet mask.</p>

You can use gethostname followed by gethostbyname to get your local interface internal IP.
This returned IP may be different from your external IP though.  To get your external IP you would have to communicate with an external server that will tell you what your external IP is.  Because the external IP is not yours but it is your routers.
```
```
//Example: b1 == 192, b2 == 168, b3 == 0, b4 == 100
struct IPv4
{
    unsigned char b1, b2, b3, b4;
};

bool getMyIP(IPv4 & myIP)
{
    char szBuffer[1024];

    #ifdef WIN32
    WSADATA wsaData;
    WORD wVersionRequested = MAKEWORD(2, 0);
    if(::WSAStartup(wVersionRequested, &wsaData) != 0)
        return false;
    #endif

    if(gethostname(szBuffer, sizeof(szBuffer)) == SOCKET_ERROR)
    {
      #ifdef WIN32
      WSACleanup();
      #endif
      return false;
    }

    struct hostent *host = gethostbyname(szBuffer);
    if(host == NULL)
    {
      #ifdef WIN32
      WSACleanup();
      #endif
      return false;
    }

    //Obtain the computer's IP
    myIP.b1 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b1;
    myIP.b2 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b2;
    myIP.b3 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b3;
    myIP.b4 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b4;

    #ifdef WIN32
    WSACleanup();
    #endif
    return true;
}
```
```
You can also always just use 127.0.0.1 which represents the local machine always.
Subnet mask in Windows:
You can get the subnet mask (and gateway and other info) by querying subkeys of this registry entry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
Look for the registry value SubnetMask.
Other methods to get interface information in Windows:
You could also retrieve the information you're looking for by using:
WSAIoctl
with this option: SIO_GET_INTERFACE_LIST