我想从控制台应用程序中找出我的IP地址。
我通常使用Request.ServerVariables
集合和/或 Request.UserHostAddress
在Web应用程序中获取IP地址。
在控制台应用程序中,如何完成这项任务呢?
我想从控制台应用程序中找出我的IP地址。
我通常使用Request.ServerVariables
集合和/或 Request.UserHostAddress
在Web应用程序中获取IP地址。
在控制台应用程序中,如何完成这项任务呢?
最简单的方法是按照以下步骤进行:
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等),所以这并不像您提出的问题那么简单。
使用Dns.GetHostName()获得主机名,然后使用Dns.GetHostAddresses()获取IPAddress数组。
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;
}
}
应该使用System.Net.Dns.GetHostAddresses()。