IP 및 호스트 이름으로 같은 망내에 있는 PC의 MacAddress를 얻어오는 코드입니다.
static class MacAddressProvider { const int PING_TIMEOUT = 1000;
[DllImport("iphlpapi.dll", ExactSpelling = true)] static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);
// ********************************************************************* /// <summary> /// Gets the MAC address from ARP table in colon (:) separated format. /// </summary> /// <param name="hostNameOrAddress">Host name or IP address of the /// remote host for which MAC address is desired.</param> /// <returns>A string containing MAC address; null if MAC address could /// not be found.</returns> public static string GetMACAddressFromARP(string hostNameOrAddress) { if (!IsHostAccessible(hostNameOrAddress)) return null;
IPHostEntry hostEntry = Dns.GetHostEntry(hostNameOrAddress);
if (hostEntry.AddressList.Length == 0) return null;
byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;
if (SendARP((int)hostEntry.AddressList[0].Address, 0, macAddr, ref macAddrLen) != 0) return null;
StringBuilder macAddressString = new StringBuilder(); for (int i = 0; i < macAddr.Length; i++) { if (macAddressString.Length > 0) macAddressString.Append(":"); macAddressString.AppendFormat("{0:x2}", macAddr[i]); } return macAddressString.ToString(); }
// ********************************************************************* /// <summary> /// Checks to see if the host specified by /// <paramref name="hostNameOrAddress"/> is currently accessible. /// </summary> /// <param name="hostNameOrAddress">Host name or IP address of the /// remote host for which MAC address is desired.</param> /// <returns><see langword="true" /> if the host is currently accessible; /// <see langword="false"/> otherwise.</returns> private static bool IsHostAccessible(string hostNameOrAddress) { Ping ping = new Ping(); PingReply reply = ping.Send(hostNameOrAddress, PING_TIMEOUT); return reply.Status == IPStatus.Success; } }
|
'.Net > Winform' 카테고리의 다른 글
C# WebBrowser IE 버젼 변경 (0) | 2013.09.06 |
---|---|
[펌]윈도우 7 테스크바를 활용한 애플리케이션 개발 (0) | 2013.08.22 |
C# Process간 메세지 전송 SendMessage (0) | 2013.07.17 |
C# Winform에서 DaumAPI 사용하기[3]_Focus 버그 수정 (0) | 2013.02.27 |
C# 응용 프로그램 관리자 권한으로 실행하기 (1) | 2013.02.19 |