Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notification of when a network interface is ready on Windows

How do I receive notification when a network interface is brought up and ready, under Windows XP?

Ready means the interface already obtained a network IP address via DHCP and is ready to use.

like image 897
unixman83 Avatar asked Dec 28 '10 14:12

unixman83


2 Answers

You can definitely get an event when an interface is ready! Just use IPHelper! The function you shall be looking for is NotifyAddrChange http://msdn.microsoft.com/en-us/library/aa366329%28v=VS.85%29.aspx and it is available starting from Windows 2000. When an adapter is up and running, it will be assigned an IP address, and thus triggered the callback.

A GetAdapterAddress can be used when triggered to figure the information you need. On Vista or above there is NotifyIpInterfaceChange that directly tell which adapter has IP change.

like image 187
Peon the Great Avatar answered Nov 12 '22 13:11

Peon the Great


You can use GetAdaptersAddresses to receive status of all adapters, then check if it is up or down. You'll have to repeat the process till the status changes. I'm not aware of any way to receive notification.

ULONG nFlags        = 0;
DWORD dwVersion     = ::GetVersion();
DWORD dwMajorVersion= (DWORD)(LOBYTE(LOWORD(dwVersion)));
if (dwMajorVersion>=6)  // flag supported in Vista and later
    nFlags= 0x0100;     // GAA_FLAG_INCLUDE_ALL_INTERFACES*/

// during system initialization, GetAdaptersAddresses may return ERROR_BUFFER_OVERFLOW and supply nLen,
// but in a subsequent call it may return ERROR_BUFFER_OVERFLOW and supply greater nLen !
ULONG nLen= sizeof (IP_ADAPTER_ADDRESSES);
BYTE* pBuf= NULL;
DWORD nErr= 0   ;
do
{
    delete[] pBuf;
    pBuf= new BYTE[nLen];
    nErr= ::GetAdaptersAddresses(AF_INET, nFlags, NULL, (IP_ADAPTER_ADDRESSES*&)pBuf, &nLen);
}
while (ERROR_BUFFER_OVERFLOW == nErr);

if (NO_ERROR != nErr)
{
    delete[] pBuf;
    // report GetAdaptersAddresses failed
    return false;
}

const IP_ADAPTER_ADDRESSES* pAdaptersAddresses= (IP_ADAPTER_ADDRESSES*&)pBuf;

while (pAdaptersAddresses) // for each adapter
{
    // todo: check if this is your adapter...
    // pAdaptersAddresses->AdapterName 
    // pAdaptersAddresses->Description 
    // pAdaptersAddresses->FriendlyName

    const IF_OPER_STATUS& Stat= pAdaptersAddresses->OperStatus; // 1:up, 2:down...

    pAdaptersAddresses= pAdaptersAddresses->Next;
}

delete[] pBuf;
return false;

Also, for each adapter you can search it's IP address in the registry. That would be in SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces##ADAPTERNAME##, Were ##ADAPTERNAME## is the AdapterName member of the IP_ADAPTER_ADDRESSES structure. Check the EnableDHCP to find if it is a dynamic address, then look at the DhcpIPAddress key.

like image 36
Lior Kogan Avatar answered Nov 12 '22 14:11

Lior Kogan