Search code examples
c++windowssocketsnetwork-programmingmac-address

How to get the MAC address of my local network interface by win socket or remote ip


Is there a way to get the MAC address (physical address) of my network interface, through which the socket connection passes, having win socket and remote ip. That is, we have a SOCKET through which we connect to a remote server, and we need to find out which network interface my local machine is connected to and which MAC it has. Not remote MAC.

In a situation where we have 2 or more network interfaces, we cannot reliably understand that the connection was made using the main adapter.

We have ifreq and <arpa/inet.h> on Linux - Finding MAC address from IP address But I couldn't find a similar solution under Windows Where do I get arpa/inet.h?

We have https://learn.microsoft.com/ru-ru/windows/win32/api/winsock2/nf-winsock2-getsockopt with SOL_SOCKET with SO_PROTOCOL_INFO. But it's not.

We have IPX_ADDRESS but we use TCP/IP

I will be grateful for your help, as I have not been able to figure it out for 3 days


Solution

  • If you have a connected (or bound) socket, you can call getsockname() to find out the socket's local IP address.

    Once you have the socket's local IP address, all you need to do is figure out which local NIC is associated with that IP address, and then find out the MAC address associated with that local NIC.

    As Mestkon mentioned in his comment, you can call GetAdaptersAddresses() to obtain information about the local NICs, then it's just a matter of looking through the returned structs to find the specific values you are interested in; e.g. for the MAC address you want the PhysicalAddress field of the PIP_ADAPTER_ADDRESSES associated with your IP address.

    If you'd like to see some example code that does this sort of thing, take a look at lines 1993-2092 of this file (that I wrote as part of my networking library); in particular look at the way the local variable mac is set at line 2067, to contain the MAC address of a local NIC.