现在的位置: 首页 > 综合 > 正文

使用IPAddress类与IPEndPoint类

2012年10月05日 ⁄ 综合 ⁄ 共 1654字 ⁄ 字号 评论关闭

转自:http://home.51.com/stevensohu/diary/item/10026158.html

另一篇关于IPV6 的文章 http://www.cnblogs.com/shanyou/archive/2011/10/09/2204333.html

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Net;
using System.Net.Sockets;
//.Net在命名空间System.Net中定义了
//IPAddress和IPEndPoint两个类来处理各种IP地址信息
namespace ConsoleApplication1
{
    class Program
    {
        public static void Main(string[] args)
        {
            IPAddress ipa1 = IPAddress.Parse("172.26.10.1");//将地址字符串转换为IPAddress实例
            Console.WriteLine("测试IP:{0}", ipa1);
            IPAddress ip2 = IPAddress.Loopback;//回送地址
            Console.WriteLine("回路地址:{0}",ip2);
            IPAddress ip3 = IPAddress.Broadcast;//IP广播地址
            Console.WriteLine("广播地址:{0}",ip3);
            IPAddress ip4 = IPAddress.Any;//提供一个IP地址,指示服务器应侦听所有网络接口上的客户端活动
            Console.WriteLine("The ANY address is:{0}",ip4.ToString());
            IPAddress ip5 = IPAddress.None;//表示不指定系统的任何网络接口
            Console.WriteLine("The NONE address is:{0}", ip5.ToString());
            string hostName = Dns.GetHostName();
            IPHostEntry hostInfo = Dns.GetHostByName(hostName);
            IPAddress localIP = hostInfo.AddressList[0];
            Console.WriteLine("本地IP:{0}", localIP);
            if (IPAddress.IsLoopback(ip2))//判断一个IP地址是否是回送地址
            {
                Console.WriteLine("The Loopback address is:{0}\n", ip2);
            }
            else
            {
                Console.WriteLine("Error obtaining the loopback adress");
            }
            if (localIP.Equals(ip2))//比较两个IP地址
            {
                Console.WriteLine("回路地址与本地地址一样");
            }
            else
            {
                Console.WriteLine("回路地址不是本址地址");
            }
        }
    }
}
从输出结果知道,IPAddress实例的Any地址为0.0.0.0,None地址为255.255.255.255。
当一个系统有多个网络接口而你不想将一个套接字只绑定到其中的一个接口时,可以使用用前者(Any);当你需要创建一个虚拟套接字而不希望将它绑定到任何一个接口时,使用后者(None)。

抱歉!评论已关闭.