Skip to content

Instantly share code, notes, and snippets.

@jymcheong
Created January 9, 2018 08:02
Show Gist options
  • Save jymcheong/90ed4d4aeafaab1fd693cb5a68dfa7a7 to your computer and use it in GitHub Desktop.
Save jymcheong/90ed4d4aeafaab1fd693cb5a68dfa7a7 to your computer and use it in GitHub Desktop.
Console test harness to get Physical Address to IP addresses (v4 & 6) mapping
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using Newtonsoft.Json;
namespace ConsoleMacAddressTest
{
class NetworkAddressMappings
{
public string PhysicalAddress
{
get;
set;
}
public List<string> IPAddresses;
public NetworkAddressMappings()
{
IPAddresses = new List<string>();
}
public static string GetAllMappings()
{
string macAddress = string.Empty;
List<NetworkAddressMappings> lstMappings = new List<NetworkAddressMappings>();
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
macAddress = nic.GetPhysicalAddress().ToString();
if (macAddress != string.Empty)
{
NetworkAddressMappings am = new NetworkAddressMappings();
am.PhysicalAddress = macAddress;
List<string> addresses = new List<string>();
foreach (UnicastIPAddressInformation ip in nic.GetIPProperties().UnicastAddresses)
am.IPAddresses.Add(ip.Address.ToString());
lstMappings.Add(am);
}
}
}
return JsonConvert.SerializeObject(lstMappings, Formatting.Indented);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(NetworkAddressMappings.GetAllMappings());
NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(AddressChangedCallback);
Console.ReadKey();
}
// this handles changes regardless DHCP or manual...
static void AddressChangedCallback(object sender, EventArgs e)
{
Console.WriteLine(NetworkAddressMappings.GetAllMappings());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment