Get IP address in a console application

2019-03-24 06:10发布

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 and/or Request.UserHostAddress.

How can this be done in a console app?

6条回答
时光不老,我们不散
2楼-- · 2019-03-24 06:21

System.Net.Dns.GetHostAddresses() should do it.

查看更多
男人必须洒脱
3楼-- · 2019-03-24 06:23

The System.Net namespace is your friend here. In particular, APIs such as DNS.GetHostByName.

However, any given machine may have multiple IP addresses (multiple NICs, IPv4 and IPv6 etc) so it's not quite as simple a question as you pose.

查看更多
forever°为你锁心
4楼-- · 2019-03-24 06:23

IPAddress[] addresslist = Dns.GetHostAddresses(Dns.GetHostName());

查看更多
劳资没心,怎么记你
5楼-- · 2019-03-24 06:30

Try this:

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());    
}
查看更多
冷血范
6楼-- · 2019-03-24 06:36

The easiest way to do this is as follows:

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();
        }
    }
}
查看更多
时光不老,我们不散
7楼-- · 2019-03-24 06:39
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

查看更多
登录 后发表回答