Learning System.Net 001
1.Creating an instance of IPAddress (using System.Net; is required)
IPAddress ipAddress = IPAddress.Parse("192.168.0.99");
youknow,”192.168.0.99” is an ip address string,this is right
but,if you use “www.baidu.com”,or even “localhost”,a FormatException occurs.
so a nicer design should be:
try
{//wrong
IPAddress ipAddress = IPAddress.Parse("localhost");
}
catch (FormatException ex)
{//the alert text should be “指定了无效的 IP 地址”
MessageBox.Show(ex.Message);
}
2.using Dns
<1>get the host name:
string strLocalHostName = Dns.GetHostName();
<2>
//obviously,this synatx is obsoleted
IPHostEntry ipHostEntry = Dns.Resove(“www.microsoft.com”);
//we’d better use this
IPHostEntry ipHostEntry = Dns.GetHostEntry(“www.microsoft.com”);
<3>
foreach(IPAddress ip in ipHostEntry.AddressList)
{
Show(ip.ToString());
}
generally speaking the ipHostEntry.AddressList[0],will be the one will usually need.
浙公网安备 33010602011771号