■ NetworkInterface 클래스의 GetAllNetworkInterfaces 정적 메소드를 사용해 호스트 IP 주소를 구하는 방법을 보여준다.
▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; #region 호스트 IP 주소 구하기 - GetHostIPAddress() /// <summary> /// 호스트 IP 주소 구하기 /// </summary> /// <returns>호스트 IP 주소</returns> public string GetHostIPAddress() { UnicastIPAddressInformation mostSuitableUnicastIPAddressInformation = null; NetworkInterface[] networkInterfaceArray = NetworkInterface.GetAllNetworkInterfaces(); foreach(NetworkInterface networkInterface in networkInterfaceArray) { if(networkInterface.OperationalStatus != OperationalStatus.Up) { continue; } IPInterfaceProperties ipInterfaceProperties = networkInterface.GetIPProperties(); if(ipInterfaceProperties.GatewayAddresses.Count == 0) { continue; } foreach(UnicastIPAddressInformation unicastIPAddressInformation in ipInterfaceProperties.UnicastAddresses) { if(unicastIPAddressInformation.Address.AddressFamily != AddressFamily.InterNetwork) { continue; } if(IPAddress.IsLoopback(unicastIPAddressInformation.Address)) { continue; } if(!unicastIPAddressInformation.IsDnsEligible) { if(mostSuitableUnicastIPAddressInformation == null) { mostSuitableUnicastIPAddressInformation = unicastIPAddressInformation; } continue; } if(unicastIPAddressInformation.PrefixOrigin != PrefixOrigin.Dhcp) { if(mostSuitableUnicastIPAddressInformation == null || !mostSuitableUnicastIPAddressInformation.IsDnsEligible) { mostSuitableUnicastIPAddressInformation = unicastIPAddressInformation; } continue; } return unicastIPAddressInformation.Address.ToString(); } } return mostSuitableUnicastIPAddressInformation != null ? mostSuitableUnicastIPAddressInformation.Address.ToString() : string.Empty; } #endregion |