Winsock Programmer's FAQ
Example: Getting the Local IP Address

This example shows how to get the local machine's IP addresses. Yes, "addresses," plural. Essentially all TCP/IP machines have at least two addresses, one for the loopback interface (127.0.0.1) and one or more for the "normal" network interfaces. The loopback interface lets two programs running on a single machine talk to each other without involving hardware drivers.

Additionally, many machines have more than one "normal" network interface. On my home machine, for example, there is one IP address for the Ethernet network board, and one for the modem when it's connected to my ISP.

The loop near the bottom of the doit() function ensures that all of these interfaces are listed.

If you want to programmatically pick one of these interfaces intelligently, you're more or less on your own. Often you end up asking to the user to pick one.

getlocalip.cpp

// Borland C++ 5.0: bcc32.cpp getlocalip.cpp
// Visual C++ 5.0: cl getlocalip.cpp wsock32.lib

#include <iostream.h>
#include <winsock.h>

int doit(int, char **)
{
    char ac[80];
    if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) {
        cerr << "Error " << WSAGetLastError() <<
                " when getting local host name." << endl;
        return 1;
    }
    cout << "Host name is " << ac << "." << endl;

    struct hostent *phe = gethostbyname(ac);
    if (phe == 0) {
        cerr << "Yow! Bad host lookup." << endl;
        return 1;
    }

    for (int i = 0; phe->h_addr_list[i] != 0; ++i) {
        struct in_addr addr;
        memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
        cout << "Address " << i << ": " << inet_ntoa(addr) << endl;
    }
    
    return 0;
}

int main(int argc, char *argv[])
{
    WSAData wsaData;
    if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
        return 255;
    }

    int retval = doit(argc, argv);

    WSACleanup();

    return retval;
}


<< Passing Sockets Between Processes Get Interface Information >>
Last modified on 22 September 2001 at 23:48 UTC-7 Please send corrections to tangent@cyberport.com.
< Go to the main FAQ page << Go to the Home Page