HappyWeasel
C# - IP return 함수 본문
//사설 ip
public static string GetInternalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
//공인 ip
#region GetRealIpAddress
private string 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.ToString();
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
'Basic > C# (.NET)' 카테고리의 다른 글
C# - Form 창 크기 잠금 (0) | 2019.04.24 |
---|---|
C# - 암호화 (SHA256) (0) | 2019.04.22 |
C# - Splash Window (Loading Form) 만들기 (0) | 2019.04.11 |
C# - Thread (0) | 2019.04.11 |
C# - 부모 폼, 자식 폼 데이터 전송 (0) | 2019.04.10 |
Comments