상세 컨텐츠

본문 제목

C#에서 NIC가 여러개 있을 때 실제 IP 구하는 방법

C#

by 탑~! 2013. 7. 1. 11:06

본문

컴퓨터에 가상 랜카드를 포함해서 랜카드가 여러개 있을 때

어떤 IP가 실제로 외부와 연결할 수 있는 IP인지 확인하는 방법이다.

 

127.0.0.1(Loopback AddresS), 169.254.x.x(Zero Configuration Networking) 등이 있어도

실제로 외부로 나가는 IpAddress를 구할 수 있다.

 

본인 랜카드가 2개이고, 둘다 유효한 IP가 할당이 되어 있고,

VMWare의 가상 랜카드도 2개가 있다. 물론 C 클래스의 유효한 IP가 할당되어 있다.

IP6도 사용하는 상태의 복잡한 상태인데도 사용하는 IP Address를 정확히 구한다.

 

게이트웨이를 통해서 나가는 값을 구하는 방식이다.

자세한 설명은 원문을 참고하시길...

 

원문 : http://stackoverflow.com/questions/1069103/how-to-get-my-own-ip-address-in-c/10774826#10774826

 

사용법은 간단하다.

 

var ipAddress = GetRealIpAddress();

#region GetRealIpAddress

private IPAddress GetRealIpAddress()

{

IPAddress gateway = FindGetGatewayAddress();

 

if (gateway == null)

return null;

 

IPAddress[] pIPAddress = Dns.GetHostAddresses(Dns.GetHostName());

 

foreach (IPAddress address in pIPAddress)

if (IsAddressOfGateway(address, gateway))

return address;

 

return null;

}

 

private bool IsAddressOfGateway(IPAddress address, IPAddress gateway)

{

if (address != null && gateway != null)

return IsAddressOfGateway(address.GetAddressBytes(), gateway.GetAddressBytes());

 

return false;

}

 

private bool IsAddressOfGateway(byte[] address, byte[] gateway)

{

if (address != null && gateway != null)

{

int gwLen = gateway.Length;

 

if (gwLen > 0)

{

if (address.Length == gateway.Length)

{

--gwLen;

int counter = 0;

 

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

{

if (address[i] == gateway[i])

++counter;

}

 

return (counter == gwLen);

}

}

}

 

return false;

}

 

private IPAddress FindGetGatewayAddress()

{

IPGlobalProperties ipGlobProps = IPGlobalProperties.GetIPGlobalProperties();

 

foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())

{

IPInterfaceProperties ipInfProps = ni.GetIPProperties();

 

foreach (GatewayIPAddressInformation gi in ipInfProps.GatewayAddresses)

return gi.Address;

}

 

return null;

}

#endregion

출처 : http://xyz37.blog.me/50156950846


관련글 더보기