题
我期待找出我的IP地址是从一个控制台应用程序是什么。
我通过使用Request.ServerVariables
收集和/或使用Request.UserHostAddress
到Web应用程序。
如何能在这样一个控制台应用程序来完成?
解决方案
做到这一点的最简单的方法如下:
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命名空间是你的朋友在这里。特别地,API,如DNS.GetHostByName。
然而,任何给定的机器可能有多个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;
}
}
不隶属于 StackOverflow