C#积木模块ABC:6.获取主机的IP地址

6.获取主机的IP地址

 

可以用.Net的DNS类来获取一个主机名或一个给定主机的IP地址。要想在程序中使用DNS类,就需要包含System.Net:


Include System.Net Reference


比如说想获取http://www.mindcracker.com/的IP地址,以下代码就会完成这个任务:


// Call DNS.GetHostName to get IPHostEntry and get the IP address list.

IPHostEntry ipEntry = DNS.GetHostByName ("www.mindcracker.com");


IPAddress [] IpAddr = ipEntry.AddressList;

 

for (int i = 0; i < IpAddr.Length; i++)


{


Console.WriteLine ("IP Address {0}: {1} ", i, IpAddr[i].ToString ());


}


另外,使用无参数的GetHostName可以返回本地机器的主机名:


string strHostName = DNS.GetHostName ();


然后将这个主机名作为参数传递给GetHostByName,就可以获取本地机器的IP地址信息。

posted @ 2008-08-08 14:55  行动  阅读(146)  评论(0)    收藏  举报