使用IPAddress類與IPEndPoint類

來源:互聯網
上載者:User

轉自: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)。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.