如何动态获取服务器(要连接的 PC)的 IP 地址?
Dee
问问题
9604 次
5 回答
17
System.Dns.GetHostEntry可用于将名称解析为 IP 地址。
于 2009-06-22T22:42:10.403 回答
10
IPHostEntry Host = Dns.GetHostEntry(DNSNameString);
DoSomethingWith(Host.AddressList);
于 2009-06-22T22:47:11.470 回答
2
如果您使用以下方法,您将能够正确解决
public static bool GetResolvedConnecionIPAddress(string serverNameOrURL, out IPAddress resolvedIPAddress)
{
bool isResolved = false;
IPHostEntry hostEntry = null;
IPAddress resolvIP = null;
try
{
if (!IPAddress.TryParse(serverNameOrURL, out resolvIP))
{
hostEntry = Dns.GetHostEntry(serverNameOrURL);
if (hostEntry != null && hostEntry.AddressList != null && hostEntry.AddressList.Length > 0)
{
if (hostEntry.AddressList.Length == 1)
{
resolvIP = hostEntry.AddressList[0];
isResolved = true;
}
else
{
foreach (IPAddress var in hostEntry.AddressList)
{
if (var.AddressFamily == AddressFamily.InterNetwork)
{
resolvIP = var;
isResolved = true;
break;
}
}
}
}
}
else
{
isResolved = true;
}
}
catch (Exception ex)
{
}
finally
{
resolvedIPAddress = resolvIP;
}
return isResolved;
}
于 2012-08-15T07:13:18.110 回答
0
你想做一个nslookup。
这是一个例子:
http://www.c-sharpcorner.com/UploadFile/DougBell/NSLookUpDB00112052005013753AM/NSLookUpDB001.aspx
于 2009-06-22T22:42:30.343 回答
0
根据您对混乱答案的评论,您不需要服务器的 IP 地址,而是需要客户端的 IP 地址。如果是这种情况,请解决您的问题……您的答案将是 HttpRequest.UserHostAddress。
于 2009-06-22T23:27:32.513 回答