代码改变世界

.net网络编程(1)Ip地址

2011-02-15 15:05  Clingingboy  阅读(890)  评论(0编辑  收藏  举报

 

转载

.NET 4.0 网络开发入门之旅系列文章”—— IP 知多少?(上)

.NET 4.0 网络开发入门之旅系列文章”—— IP 知多少?(下)

一.IPAddress

public static void Main()
{
    //创建5个IPAddress对象,并赋值
    IPAddress newaddress1 = IPAddress.Parse("192.168.1.1");
    IPAddress newaddress2 = IPAddress.Loopback;
    IPAddress newaddress3 = IPAddress.Broadcast;
    IPAddress newaddress4 = IPAddress.Any;
    IPAddress newaddress5 = IPAddress.None;

    /*用System.net.dns类中的GetHostByName()和GetHostName()方法来建立一个本
    地IP地址,并且建立了一个IPHostEntry对象。用以下两句代码来获取本地IP
    地址*/

    IPHostEntry here = Dns.GetHostByName(Dns.GetHostName());
    IPAddress localaddress = here.AddressList[0];

    //判断newaddress2地址是否为环回地址
    if (IPAddress.IsLoopback(newaddress2))
        Console.WriteLine("The Loopback address is: {0}", newaddress2.ToString());
    else
        Console.WriteLine("Error obtaining the loopback address");

    //打印本地IP地址
    Console.WriteLine("The Local IP address is: {0}\n", localaddress.ToString());

    //判断本地IP地址是否为环回地址
    if (localaddress == newaddress2)
        Console.WriteLine("The loopback address is the same as local address.\n");
    else
        Console.WriteLine("The loopback address is not the local address.\n");

    //打印其他IP地址
    Console.WriteLine("The test address is: {0}", newaddress1.ToString());
    Console.WriteLine("Broadcast address: {0}", newaddress3.ToString());
    Console.WriteLine("The ANY address is: {0}", newaddress4.ToString());
    Console.WriteLine("The NONE address is: {0}", newaddress5.ToString());

    //用console.readling()使程序在执行完上述代码后不立即退出,在用户输入回车键之后退出程序

    Console.ReadLine();
}

image

二.DNS(Domain Name System)

提供域名解析功能

IPHostEntry results = Dns.GetHostEntry("www.cnblogs.com");
Console.WriteLine("Host name: {0}", results.HostName);
foreach (string alias in results.Aliases)
{
    Console.WriteLine("Alias: {0}", alias);
}
foreach (IPAddress address in results.AddressList)
{
    Console.WriteLine("Address: {0}", address.ToString());
}

image

 

三.IP终结点

包含IP同时,还有一个端口号

public static void Main()
{
    IPAddress newaddress = IPAddress.Parse("192.168.1.1");
    //创建IPEndPoint实例
    IPEndPoint ex = new IPEndPoint(newaddress, 8000);
    Console.WriteLine("The IPEndPoint is:{0}", ex.ToString());
    Console.WriteLine("The AddressFamily is:{0}", ex.AddressFamily);
    Console.WriteLine("The Address is:{0},and the port is:{1}", ex.Address, ex.Port);
    Console.WriteLine("The Min Port Number is:{0}", IPEndPoint.MinPort);
    Console.WriteLine("The Max Port Number is:{0}", IPEndPoint.MaxPort);
    //用port属性单独改变IPEndPoint对象的端口值
    ex.Port = 80;
    Console.WriteLine("The changed IPEndPoint vaule is:{0}", ex.ToString());
    //存储IPEdnPoint实例
    SocketAddress sa = ex.Serialize();
    Console.WriteLine("The Socketaddress is:{0}", sa.ToString());
    Console.ReadLine();
}

image