[C#] C # 응용 프로그램이 실행되는 서버의 IP 주소를 얻는 방법은 무엇입니까?

서버를 실행 중이며 내 자신의 IP 주소를 표시하고 싶습니다.

컴퓨터 자체 (가능한 경우) 외부 IP 주소를 얻는 구문은 무엇입니까?

누군가 다음 코드를 작성했습니다.

IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
    if (ip.AddressFamily.ToString() == "InterNetwork")
    {
        localIP = ip.ToString();
    }
}
return localIP;

그러나 나는 일반적으로 저자를 불신하며이 코드를 이해하지 못한다. 더 좋은 방법이 있습니까?



답변

아니, 그게 가장 좋은 방법입니다. 머신에 여러 개의 IP 주소 있을 수 있으므로 적절한 IP 주소를 찾으려면 해당 콜렉션을 반복해야합니다.

편집 : 내가 유일한 변경이 설정을 변경하는 것입니다 :

if (ip.AddressFamily.ToString() == "InterNetwork")

이에:

if (ip.AddressFamily == AddressFamily.InterNetwork)

ToString비교 를 위해 열거 할 필요가 없습니다 .


답변

공개 IP를 아는 유일한 방법은 다른 사람에게 당신에게 말하도록 요청하는 것입니다. 이 코드는 당신을 도울 수 있습니다 :

public string GetPublicIP()
{
    String direction = "";
    WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
    using (WebResponse response = request.GetResponse())
    using (StreamReader stream = new StreamReader(response.GetResponseStream()))
    {
        direction = stream.ReadToEnd();
    }

    //Search for the ip in the html
    int first = direction.IndexOf("Address: ") + 9;
    int last = direction.LastIndexOf("</body>");
    direction = direction.Substring(first, last - first);

    return direction;
}


답변

하나의 솔루션으로 모든 것을 깨끗하게 청소하십시오 : D

//This returns the first IP4 address or null
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);


답변

나에게 일어난 DNS 서버에서 IP 주소를 얻는 것에 의존 할 수 없다면 다음과 같은 방법을 사용할 수 있습니다.

System.Net.NetworkInformation 네임 스페이스에는 정적 GetAllNetworkInterfaces 메서드 가있는 NetworkInterface 클래스 가 포함되어 있습니다 .

이 방법은 컴퓨터의 모든 “네트워크 인터페이스”를 반환하며 컴퓨터에 무선 어댑터 및 / 또는 이더넷 어댑터 하드웨어 만 설치되어 있어도 일반적으로 몇 가지가 있습니다. 이 네트워크 인터페이스는 모두 로컬 컴퓨터에 유효한 IP 주소를 가지고 있지만 아마도 하나만 원할 수도 있습니다.

하나의 IP 주소를 찾고 있다면 올바른 주소를 식별 할 수있을 때까지 목록을 필터링해야합니다. 아마도 몇 가지 실험을해야하지만 다음과 같은 접근 방식으로 성공했습니다.

  • 를 확인하여 비활성화 된 모든 네트워크 인터페이스를 필터링하십시오 OperationalStatus == OperationalStatus.Up. 예를 들어 네트워크 케이블이 연결되어 있지 않으면 실제 이더넷 어댑터가 제외됩니다.

각 NetworkInterface에 대해 GetIPProperties 메소드를 사용하여 IPInterfaceProperties 오브젝트를 얻을 수 있으며 IPInterfaceProperties 오브젝트 에서 UnicastIPAddressInformation 오브젝트 목록에 대한 UnicastAddresses 특성 에 액세스 할 수 있습니다 .

  • 다음을 확인하여 선호하지 않는 유니 캐스트 주소를 필터링하십시오. DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
  • 를 확인하여 “가상”주소를 필터링하십시오 AddressPreferredLifetime != UInt32.MaxValue.

이 시점에서 필자는이 필터들 모두와 일치하는 첫 번째 (있는 경우) 유니 캐스트 주소의 주소를 가져옵니다.

편집하다:

[중복 주소 감지 상태 및 선호 수명에 대해 위의 텍스트에 언급 된 조건을 포함하도록 2018 년 5 월 16 일에 개정 된 코드]

아래 샘플은 작동 상태, 주소 패밀리, 루프백 주소 (127.0.0.1) 제외, 중복 주소 감지 상태 및 선호 수명을 기준으로 필터링을 보여줍니다.

static IEnumerable<IPAddress> GetLocalIpAddresses()
{
    // Get the list of network interfaces for the local computer.
    var adapters = NetworkInterface.GetAllNetworkInterfaces();

    // Return the list of local IPv4 addresses excluding the local
    // host, disconnected, and virtual addresses.
    return (from adapter in adapters
            let properties = adapter.GetIPProperties()
            from address in properties.UnicastAddresses
            where adapter.OperationalStatus == OperationalStatus.Up &&
                  address.Address.AddressFamily == AddressFamily.InterNetwork &&
                  !address.Equals(IPAddress.Loopback) &&
                  address.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred &&
                  address.AddressPreferredLifetime != UInt32.MaxValue
            select address.Address);
}


답변

WebClient webClient = new WebClient();
string IP = webClient.DownloadString("http://myip.ozymo.com/");


답변

using System.Net;

string host = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(host);
Console.WriteLine(ip.AddressList[0].ToString());

내 컴퓨터에서 이것을 테스트하고 작동합니다.


답변

DNS를 사용하지 않으려면 다음을 수행하십시오.

List<IPAddress> ipList = new List<IPAddress>();
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
    foreach (var address in netInterface.GetIPProperties().UnicastAddresses)
    {
        if (address.Address.AddressFamily == AddressFamily.InterNetwork)
        {
            Console.WriteLine("found IP " + address.Address.ToString());
            ipList.Add(address.Address);
        }
    }
}