【问题标题】:How to get IP of computer on lan if you have the computers name, using c#如果您有计算机名称,如何使用c#获取局域网上计算机的IP
【发布时间】:2013-07-03 10:27:41
【问题描述】:

我目前正在编写一个 C# 程序来将一台计算机连接到局域网上的另一台计算机。 我有接收计算机的计算机名称,但 ip 是动态的,因此会不时更改。

如何获取接收计算机的局域网 IP 地址? (类似 192.168.1.# 的那个)

【问题讨论】:

标签: c# ip lan


【解决方案1】:

假设根据您的假设您正在寻找第一个 IPv4 ip 地址,您可以使用以下内容:

String name = "Name";
IPHostEntry ipHostInfo = Dns.GetHostEntry(name);            
// OR you can get the name of the current computer using 
// IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());                

// Get the first IPv4 address
IPAddress ip = ipHostInfo.AddressList.Where(n => n.AddressFamily == AddressFamily.InterNetwork).First();

【讨论】:

  • 我似乎无法让“.Where”部分工作它无法识别。
  • 4.5 它是特定命名空间的一部分吗?
  • 这是 4.0 但也应该在 3.5 中工作。 Where is linq 所以你需要参考使用 System.Linq;
  • 太棒了,做到了。谢谢=)
【解决方案2】:

Dns.GetHostAddresses Method

您可以将主机名解析为 IP,如下所示

string hostName = "www.Google.com";
IPAddress[] addresslist = Dns.GetHostAddresses(hostName);

foreach (IPAddress address in addresslist)
{
   string ip = address.ToString();
}

【讨论】:

    猜你喜欢
    • 2011-09-04
    • 2011-06-14
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    相关资源
    最近更新 更多