Tutorial: How to Get a List of Available Network Interfaces

Posted by Matt | Filed under , , , ,

If you're creating a network application, often you need to know if you have an active network connection to a LAN.  (Note that this is not the same thing as determining if you have a valid Internet connection.)  Winsock has a function which will let you get a list of available network interfaces:  WSAIoctl.

Using WSAIoctl, you can get a list of interfaces on the computer as well as some status information about them.  For example, it will tell you if the connection is up, loopback, point-to-point, supports multicasting, or supports broadcasting.

To get the list, you would use:

INTERFACE_INFO interfaces[32];
unsigned long nReturned = 0;
int nRet = WSAIoctl(s, // socket handle
    SIO_GET_INTERFACE_LIST, 
    0, 
    0, 
    &interfaces,
    sizeof(INTERFACE_INFO) * 32, 
    &nReturned, 
    0, 
    0);

if (nRet == SOCKET_ERROR) 
{
    int nError = WSAGetLastError();
    _tprintf(_T("Error getting interface list: %i\n"), nError);
    return;
}

After this, your list of interfaces will be in the array and the number of interfaces can be determined by:

int nNumInterfaces = nReturned / sizeof(INTERFACE_INFO);

From here, you can iterate through the interfaces checking for a connected interface.

for (int i = 0; i < nNumInterfaces; ++i) 
{
    INTERFACE_INFO *pIf = &interfaces[i];
    if ((pIf->iiFlags & IFF_LOOPBACK) != 0)
        continue;

    if ((pIf->iiFlags & IFF_UP) == 0)
        continue;

    // If you get here, you have a valid
    // interface to the LAN.
}

In the above case, we're looking for an interface that is up and not a loopback.

There is some other useful information in the INTERFACE_INFO structure:  ip address of the interface, netmask, broadcast mask, whether the connection is point-to-point, and supports multicasting or broadcasting.

I will reiterate that this does not tell you if you are connected to the Internet, nor will it tell you whether there's anything on the other end to communicate with.

Comments

August 29, 2008 11:34

trackback

Trackback from DotNetKicks.com

Tutorial: How to Get a List of Available Network Interfaces

DotNetKicks.com

Comments are closed