Last active
December 31, 2015 10:49
-
-
Save aabidos/7975605 to your computer and use it in GitHub Desktop.
C# Resolve Gateway MAC from public ip addr. Thanks to Stackoverflow community
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.Collections.Generic; | |
| using System.IO; | |
| using System.Linq; | |
| using System.Net; | |
| using System.Runtime.InteropServices; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| namespace Arp | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| var client = new WebClient(); | |
| var ipAddress = client.DownloadString("http://ipecho.net/plain"); | |
| IPAddress address = IPAddress.Parse(ipAddress); | |
| byte[] t = GetMacAddress(address); | |
| string mac = string.Join(":", (from z in t select z.ToString("X2")).ToArray()); | |
| Console.WriteLine(mac); | |
| Console.ReadLine(); | |
| } | |
| [DllImport("iphlpapi.dll", ExactSpelling = true)] | |
| public static extern int SendARP(uint destIP, uint srcIP, byte[] macAddress, ref uint macAddressLength); | |
| public static byte[] GetMacAddress(IPAddress address) | |
| { | |
| byte[] mac = new byte[6]; | |
| uint len = (uint)mac.Length; | |
| byte[] addressBytes = address.GetAddressBytes(); | |
| uint dest = ((uint)addressBytes[3] << 24) | |
| + ((uint)addressBytes[2] << 16) | |
| + ((uint)addressBytes[1] << 8) | |
| + ((uint)addressBytes[0]); | |
| if (SendARP(dest, 0, mac, ref len) != 0) | |
| { | |
| throw new Exception("The ARP request failed."); | |
| } | |
| return mac; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment