Skip to content

Instantly share code, notes, and snippets.

@dantheman213
Last active January 13, 2024 10:15
Show Gist options
  • Save dantheman213/db3118bed76199186acf7be87af0c1c4 to your computer and use it in GitHub Desktop.
Save dantheman213/db3118bed76199186acf7be87af0c1c4 to your computer and use it in GitHub Desktop.
Get primary network adapter(s) info for C#
using System;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace GetPrimaryNetworkDeviceInfoExample
{
public class Program
{
public static void Main()
{
var interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var adapter in interfaces.Where(x => x.OperationalStatus == OperationalStatus.Up))
{
if (adapter.Name.ToLower() == "ethernet" || adapter.Name.ToLower() == "wi-fi")
{
var props = adapter.GetIPProperties();
var result = props.UnicastAddresses.FirstOrDefault(x => x.Address.AddressFamily == AddressFamily.InterNetwork);
if (result != null)
{
Console.WriteLine("Name: {0}", adapter.Name);
Console.WriteLine("Status: {0}", adapter.OperationalStatus);
Console.WriteLine("MAC: {0}", adapter.GetPhysicalAddress());
var ip = result.Address.ToString();
Console.WriteLine("IP Address: {0}", ip);
var subnet = result.IPv4Mask.ToString();
Console.WriteLine("Subnet Mask: {0}", subnet);
}
}
}
}
}
}
@DavidAPalacios
Copy link

This is exactly what I needed. Great work!

@brian9206
Copy link

Line 15 will not work on every PC. Use this:

if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet || adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment