Notification of when a network interface is ready

2019-01-24 11:27发布

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.

2条回答
Rolldiameter
2楼-- · 2019-01-24 11:50

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.

查看更多
乱世女痞
3楼-- · 2019-01-24 11:51

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.

查看更多
登录 后发表回答