문제

콘솔 응용 프로그램에서 내 IP 주소가 무엇인지 알아 내려고합니다.

나는 사용하여 웹 응용 프로그램에 익숙합니다. Request.ServerVariables 수집 및/또는 Request.UserHostAddress.

콘솔 앱에서 어떻게 할 수 있습니까?

도움이 되었습니까?

해결책

이를 수행하는 가장 쉬운 방법은 다음과 같습니다.

using System;
using System.Net;


namespace ConsoleTest
{
    class Program
    {
        static void Main()
        {
            String strHostName = string.Empty;
            // Getting Ip address of local machine...
            // First get the host name of local machine.
            strHostName = Dns.GetHostName();
            Console.WriteLine("Local Machine's Host Name: " + strHostName);
            // Then using host name, get the IP address list..
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;

            for (int i = 0; i < addr.Length; i++)
            {
                Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
            }
            Console.ReadLine();
        }
    }
}

다른 팁

이 시도:

String strHostName = Dns.GetHostName();

Console.WriteLine("Host Name: " + strHostName);

// Find host by name    IPHostEntry
iphostentry = Dns.GetHostByName(strHostName);

// Enumerate IP addresses
int nIP = 0;   
foreach(IPAddress ipaddress in iphostentry.AddressList) {
   Console.WriteLine("IP #" + ++nIP + ": " + ipaddress.ToString());    
}

System.net 네임 스페이스는 여기에 친구입니다. 특히 DNS.gethostbyName과 같은 API.

그러나 주어진 기계에는 여러 IP 주소 (다중 NIC, IPv4 및 IPv6 등)가있을 수 있으므로 자세한 질문만큼 간단하지 않습니다.

iPaddress [] addressList = dns.gethostAddresses (dns.gethostName ());

System.net.dns.gethostAddresses ()가 수행해야합니다.

using System;
using System.Net;

public class DNSUtility
{
    public static int Main (string [] args)
    {

      String strHostName = new String ("");
      if (args.Length == 0)
      {
          // Getting Ip address of local machine...
          // First get the host name of local machine.
          strHostName = DNS.GetHostName ();
          Console.WriteLine ("Local Machine's Host Name: " +  strHostName);
      }
      else
      {
          strHostName = args[0];
      }

      // Then using host name, get the IP address list..
      IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
      IPAddress [] addr = ipEntry.AddressList;

      for (int i = 0; i < addr.Length; i++)
      {
          Console.WriteLine ("IP Address {0}: {1} ", i, addr[i].ToString ());
      }
      return 0;
    }    
 }

원천 : http://www.codeproject.com/kb/cs/network.aspx

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top