■ MAC 주소 구하기 예제

------------------------------------------------------------------------------------------------------------------------

string macAddress = GetMACAddress("192.168.29.196"));

------------------------------------------------------------------------------------------------------------------------

 

■ MAC 주소 구하기

------------------------------------------------------------------------------------------------------------------------

using System;

using System.Net;

using System.Runtime.InteropServices;

 

#region ARP 보내기 - SendARP(destinationIPValue, sourceIPValue, physicalAddressArray, physicalAddresArrayLength)

 

/// <summary>

/// ARP 보내기

/// </summary>

/// <param name="destinationIPValue">목적 IP 값</param>

/// <param name="sourceIPValue">소스 IP 값</param>

/// <param name="physicalAddressArray">물리적 주소 배열</param>

/// <param name="physicalAddresArrayLength">물리적 주소 배열 길이</param>

/// <returns>처리 결과</returns>

[DllImport("iphlpapi.dll", ExactSpelling = true)]

private static extern int SendARP(int destinationIPValue, int sourceIPValue, byte[] physicalAddressArray, ref uint physicalAddresArrayLength);

 

#endregion

#region MAC 주소 구하기 - GetMACAddress(ipAddressString)

 

/// <summary>

/// MAC 주소 구하기

/// </summary>

/// <param name="ipAddressString">IP 주소 문자열</param>

/// <returns>MAC 주소</returns>

public string GetMACAddress(string ipAddressString)

{

    IPAddress destinationIPAddress = IPAddress.Parse(ipAddressString);

 

    byte[] destinationIPAddressByteArray       = new byte[6];

    uint   destinationIPAddressByteArrayLength = (uint)destinationIPAddressByteArray.Length;

 

    int destinationIPValue = BitConverter.ToInt32(destinationIPAddress.GetAddressBytes(), 0);

 

    int returnCode = SendARP(destinationIPValue, 0, destinationIPAddressByteArray, ref destinationIPAddressByteArrayLength);

 

    if(returnCode != 0)

    {

        return null;

    }

 

    string[] destinationIPAddressStringArray = new string[(int)destinationIPAddressByteArrayLength];

 

    for(int i = 0; i < destinationIPAddressByteArrayLength; i++)

    {

        destinationIPAddressStringArray[i] = destinationIPAddressByteArray[i].ToString("X2");

    }

 

    string maxAddress = string.Join(":", destinationIPAddressStringArray);

 

    return maxAddress;

}

 

#endregion

------------------------------------------------------------------------------------------------------------------------

 

Posted by 사용자 icodebroker

댓글을 달아 주세요