Home > database >  Finding current connected network interface/adaptor Windows
Finding current connected network interface/adaptor Windows

Time:09-26

I'm thinking there must be a way to ask windows for information about the network adaptor of the current connected network (available unicast/multicast, is it Wi-Fi, the name, etc)

When I say connected, I mean like the current Wi-Fi connection like windows shows you in the Wi-Fi options - the definition of connected is probably different in the networking world

Even if it's just possible the interface index, because It's easy to look up most other things using GetAdaptersAddresses() etc

In case this is an x/y problem: I'm trying to do this as part of writing an mdns client (for academic purposes, I know windows has an mdns api). I'd like to only broadcast and receive on the current Wi-Fi network (for which I think you need to set the IP_ADD_SOURCE_MEMBERSHIP flag in setsockopt) and I also need to then know which IP address to return to the mdns response

I could set IP_ADD_MEMBERSHIP but then I would still need to find out which IP to return and everything just becomes conceptually easier if things work on a single network (or so I thought)

CodePudding user response:

The GetAdaptersAddresses will give you the list of network interfaces on the system and will tell you what type of interface each of them is.

In the returned IP_ADAPTER_ADDRESSES list, the IfType field tells you the type of the interface, which for wireless will be IF_TYPE_IEEE80211. Then when you find an interface of this type, you can iterate through the list of assigned addresses via the FirstUnicastAddress member to join the relevant multicast groups.

IP_ADAPTER_ADDRESSES *head, *curr;
IP_ADAPTER_UNICAST_ADDRESS *uni;
int buflen, err, i;

buflen = sizeof(IP_ADAPTER_UNICAST_ADDRESS) * 500;  //  enough for 500 interfaces
head = malloc(buflen);
if (!head) exit(1);
if ((err = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, head,
                                &buflen)) != ERROR_SUCCESS) {
    char errbuf[300];
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err,
                  0, errbuf, sizeof(errbuf), NULL);
    printf("GetAdaptersAddresses failed: (%d) %s", err, errbuf);
    free(head);
    exit(1);
}
for (curr = head; curr; curr = curr->Next) {
    if (curr->IfType != IF_TYPE_IEEE80211) continue;
    for (uni = curr->FirstUnicastAddress; uni; uni = uni->Next) {
        if (curr->OperStatus == IfOperStatusUp) {
            char addrstr[INET6_ADDRSTRLEN];

            inet_ntop(uni->Address.lpSockaddr->sa_family, uni->Address.lpSockaddr, 
                      addrstr, uni->Address.iSockaddrLength);
            printf("interface name: %s\n", curr->AdapterName);
            printf("interface address: %s\n", addrstr);
        }
    }
}
free(head);

An important note here is that there may be more that one wireless interface active.

  • Related