상세 컨텐츠

본문 제목

IP Address, MAC Address 구하기

C#

by 탑~! 2016. 2. 25. 11:21

본문



/// <summary>

/// 로컬 IP를 구해온다.

/// </summary>

/// <param name="index">랜카드 인덱스</param>

/// <returns>IP</returns>

public static string GetLocalIp(int index)

{

    return System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[index].ToString();

}

 

 

/// <summary>

/// 첫번째 로컬 IP를 구해온다.

/// </summary>

/// <returns>IP</returns>

public static string GetLocalIp()

{

    return GetLocalIp(0);

}

 

 

/// <summary>

/// IP Address에 해당하는 Mac Address를 가져온다.

/// </summary>

/// <param name="ip">찾고자 하는 IP Address</param>

/// <returns>Mac Address</returns>

public static string GetMacAddress(string ip)

{

    string rtn = string.Empty;

    ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled='TRUE'");

    ManagementObjectSearcher query1 = new ManagementObjectSearcher(oq);

    foreach (ManagementObject mo in query1.Get())

    {

        string[] address = (string[])mo["IPAddress"];

        if (address[0] == ip && mo["MACAddress"] != null)

        {

            rtn = mo["MACAddress"].ToString();

            break;

        }

    }

    return rtn;

}

 

 

/// <summary>

/// 첫번째 IPv4 값을 가져온다.

/// </summary>

/// <returns>못찾으면 null</returns>

public string GetFirstIPv4()

{

    Regex regex = new Regex(@"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");

 

    foreach (System.Net.IPAddress ip in System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList)

    {

        if (regex.IsMatch(ip.ToString()))

        {

            return ip.ToString();

        }

    }

 

    return null;

}



출처 : http://kimstar.kr/3275/

관련글 더보기