Example - Getting the Local IP Address

This example shows how to get the local machine's IP address(es). Note especially the loop near the bottom of the doit() function. Although the majority of machines have only a single IP address, it is becoming common for a machine to have two or more IP addresses. 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.


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

Back to the New User Issues page...
Back to the Examples page...


Go to my home page Go to my Important RFC Lists page Go to the main Programming Resources page

Please send updates and corrections to <tangent@cyberport.com>.