Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current used network adapter

Now I am trying to get network adapter in use among of several network adapters on my machine so that I can get ip address, mac address and adapter name of the network adapter. But I am not having any luck. What I found the solution for it is Get current network adapter in use. I dont think it is for .Net framework project but ASP.NET Core.

My code is below.

public void GetIpAndMacAddress()
{
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        // Only consider Ethernet network interfaces
        if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
            nic.OperationalStatus == OperationalStatus.Up)
        {
            IPInterfaceProperties adapterProperties = nic.GetIPProperties();
            foreach (var ip in adapterProperties.UnicastAddresses) 
            {
                if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    IPAddress = ip.Address.ToString();
            }
            string hexMac = nic.GetPhysicalAddress().ToString(),
                   regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})",
                   replace = "$1:$2:$3:$4:$5:$6";
            IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties();

            netAdapterName = nic.Name;
            MACAddress = Regex.Replace(hexMac, regex, replace);
            return;
        }
    }
}
like image 321
JS Guru Avatar asked Oct 24 '25 21:10

JS Guru


1 Answers

Following should help you.

NetworkInterface[] networks = NetworkInterface.GetAllNetworkInterfaces();

var activeAdapter = networks.First(x=> x.NetworkInterfaceType != NetworkInterfaceType.Loopback
                    && x.NetworkInterfaceType != NetworkInterfaceType.Tunnel
                    && x.OperationalStatus == OperationalStatus.Up 
                    && x.Name.StartsWith("vEthernet") == false);

The search is based on eliminating Network Adapters that are neither Loopback (Commonly used for testing) or Tunnel(commonly used for secure connection between private networks). Operational Status ensures that the Network interface is up and is is able to transmit data packets. The "vEthernet" is naming convention commonly used by Windows for Hyper-V Virtual Network Adapters

like image 86
Anu Viswan Avatar answered Oct 26 '25 09:10

Anu Viswan