我想从控制台应用程序中弄清楚我的IP地址是什么。
我习惯使用Request.ServerVariables
集合和/或Request.UserHostAddress
来使用Web应用程序。
如何在控制台应用中完成?
答案 0 :(得分:27)
最简单的方法如下:
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();
}
}
}
答案 1 :(得分:3)
试试这个:
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());
}
答案 2 :(得分:2)
System.Net命名空间是您的朋友。特别是,诸如DNS.GetHostByName。
之类的API但是,任何给定的计算机可能都有多个IP地址(多个NIC,IPv4和IPv6等),因此问题并不像你提出的那么简单。
答案 3 :(得分:2)
IPAddress [] addresslist = Dns.GetHostAddresses(Dns.GetHostName());
答案 4 :(得分:1)
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;
}
}
答案 5 :(得分:1)
System.Net.Dns.GetHostAddresses()应该这样做。