This example shows how to get the local machine’s IP addresses. Yes, “addresses,” plural. You can count on seeing at least two addresses on most machines: one for the loopback interface (127.0.0.1) and at least one for an external network interface. It is not at all uncommon for a single machine to have multiple network interfaces: a PC on a LAN with a modem connected to the Internet, for instance. The loopback interface lets two programs running on a single machine talk to each other without involving hardware drivers.

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
//
// This sample program is hereby placed in the public domain.

#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 >>
Updated Mon Sep 22 2014 20:57 MDT   Go to my home page