C#中如何得到机器的IP地址 碧血黄沙

       最近,由于设计需要,软件中需要得到机器的IP地址,并做记录。最后,我选择了用DNS类并得到机器的IP地址的方法。

       System.Net名称空间中的DNS类可以用来得到机器名称和IP地址。 DNS类提供类简单的域名解释函数。DNS 类为处理Internet域名(DNS)信息提供支持.这些返回的信息包括多重的IP地址和主机别名。返回的列表是一个集合或IPAddress对象数组。以下代码显示了如何通过给定的主机名称得到IP地址。

代码如下:

namespace Dnstilities
{
using System;
using System.Net;
public class DNS
{
public static int Main (string [] args)
{
String strHostName = new String ("");
if (args.Length == 0)
{
// 首先得到本地机器的主机名称
strHostName = DNS.GetHostName ();
Console.WriteLine ("Local Machine''s Host Name: " +  strHostName);
}
else
{
strHostName = args[0];
}
// 然后通过主机名称得到IP地址列表
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;
}
}
}
代码的解释

如果想得到本地机器的主机名,你可以不加参数调用GetHostName方法。然后你可以用返回的结果作为参数调用GetHostByName方法得到IPAddresses列表,然后遍历addresses集合得到主机的IP地址。

        好了,现在你可以记录你得到的IP了。

新站上线--咱地里 www.zandili.com 科技博客
原文地址:https://www.cnblogs.com/airfey/p/239848.html