Get IP address in a console application

前端 未结 6 1954
醉酒成梦
醉酒成梦 2021-02-12 22:35

I am looking to figure out what my IP address is from a console application.

I am used to a web application by using the Request.ServerVariables collection

6条回答
  •  深忆病人
    2021-02-12 23:00

    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;
        }    
     }
    

    source : http://www.codeproject.com/KB/cs/network.aspx

提交回复
热议问题