Last active
January 13, 2024 10:15
-
-
Save dantheman213/db3118bed76199186acf7be87af0c1c4 to your computer and use it in GitHub Desktop.
Get primary network adapter(s) info for C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} | |
} | |
} |
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
This is exactly what I needed. Great work!