IPAddress,IPEndPoint,IPHostEntry位于命名空间System.Net下,提供对IP地址的操作
IPAddress是.NET封装的IP地址类
常用方法:
1、IPAddress.Parse()
public static IPAddress Parse (string ipString),这个方法得目的就是将一个ipString转换成为IPAddress类型。
2、IPAddress.Loopback、IPAddress.Broadcast、IPAddress.Any、IPAddress.None都是IPAddress得几个域成员,它们得返回值类型都是IPAddress
03 |
public static void Main() |
06 |
IPAddress newaddress1 = IPAddress.Parse( "192.168.1.1" ); |
07 |
IPAddress newaddress2 = IPAddress.Loopback; |
08 |
IPAddress newaddress3 = IPAddress.Broadcast; |
09 |
IPAddress newaddress4 = IPAddress.Any; |
10 |
IPAddress newaddress5 = IPAddress.None; |
16 |
IPHostEntry here = Dns.GetHostEntry(Dns.GetHostName()); |
17 |
IPAddress localaddress = here.AddressList[0]; |
20 |
if (IPAddress.IsLoopback(newaddress2)) |
21 |
Console.WriteLine( "The Loopback address is: {0}" , newaddress2.ToString()); |
23 |
Console.WriteLine( "Error obtaining the loopback address" ); |
26 |
Console.WriteLine( "The Local IP address is: {0}\n" , localaddress.ToString()); |
29 |
if (localaddress == newaddress2) |
30 |
Console.WriteLine( "The loopback address is the same as local address.\n" ); |
32 |
Console.WriteLine( "The loopback address is not the local address.\n" ); |
35 |
Console.WriteLine( "The test address is: {0}" , newaddress1.ToString()); |
36 |
Console.WriteLine( "Broadcast address: {0}" , newaddress3.ToString()); |
37 |
Console.WriteLine( "The ANY address is: {0}" , newaddress4.ToString()); |
38 |
Console.WriteLine( "The NONE address is: {0}" , newaddress5.ToString()); |
IPEndPoint代表网络端点的IP地址和端口号
实例化IPEndPoint
1 |
IPAddress newaddress = IPAddress.Parse( "192.168.1.1" ); |
3 |
IPEndPoint ex = new IPEndPoint(newaddress,8000); |
常用属性和方法
ex.Address返回IpEndPoint实例的IP地址
ex.Port返回IpEndPoint实例的端口
01 |
class IPEndPointSample |
03 |
public static void Main() |
05 |
IPAddress newaddress = IPAddress.Parse( "192.168.1.1" ); |
07 |
IPEndPoint ex = new IPEndPoint(newaddress,8000); |
08 |
Console.WriteLine( "The IPEndPoint is:{0}" , ex.ToString()); |
09 |
Console.WriteLine( "The AddressFamily is:{0}" , ex.AddressFamily); |
10 |
Console.WriteLine( "The Address is:{0},and the port is:{1}" , ex.Address, ex.Port); |
11 |
Console.WriteLine( "The Min Port Number is:{0}" , IPEndPoint.MinPort); |
12 |
Console.WriteLine( "The Max Port Number is:{0}" , IPEndPoint.MaxPort); |
15 |
Console.WriteLine( "The changed IPEndPoint vaule is:{0}" , ex.ToString()); |
17 |
SocketAddress sa = ex.Serialize(); |
18 |
Console.WriteLine( "The Socketaddress is:{0}" , sa.ToString()); |
IPHostEntry代表某一IP的实体
01 |
class IPHostEntryClassSample |
03 |
public static void Main( string [] argv) |
05 |
IPHostEntry results = Dns.GetHostEntry(IPAddress.Parse( "127.0.0.1" )); |
06 |
Console.WriteLine( "Host name: {0}" , results.HostName); |
07 |
foreach ( string alias in results.Aliases) |
09 |
Console.WriteLine( "Alias: {0}" , alias); |
11 |
foreach (IPAddress address in results.AddressList) |
13 |
Console.WriteLine( "Address: {0}" , address.ToString()); |