Menü Schließen

Obtain IP and MAC Address in C#

There is no built-in way to discover the MAC address of your network adapter in .NET.

Using the following function the MAC address that belongs to any IP address can be obtained.

The functions use the external DLL iphlpapi.dll.

public static class Network
{
  [DllImport("iphlpapi.dll", ExactSpelling = true)]
  private static extern int SendARP(int DestIP, int SrcIP, [Out] byte[] pMacAddr, ref int PhyAddrLen);

  public static string GetMac(IPAddress adr) 
  {
    int a = BitConverter.ToInt32(adr.GetAddressBytes(), 0);
    byte[] ab = new byte[6];
    int len = ab.Length;
    int r = SendARP(a, 0, ab, ref len);
    return BitConverter.ToString(ab, 0, 6);
  }

  public static string GetMac(string adr) 
  {
    return GetMac(IPAddress.Parse(adr));
  }

  public static string[] GetMyIP()
  {
    IPAddress[] a = Dns.GetHostAddresses(Environment.MachineName);
    return a.Select(x => x.ToString()).ToArray();
  }
 

  public static string[] GetMyMac()
  {
    IPAddress[] a = Dns.GetHostAddresses(Environment.MachineName);
    return a.Select(x => GetMac(x)).ToArray();
  }
}

The functions GetMyIP and GetMyMac retrieve the IP address and the MAC address of the current machine.

Ähnliche Beiträge

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert