IP 層的程式設計

基礎篇

C# 簡介

開發環境

變數與運算

流程控制

陣列

函數

物件

例外處理

函式庫篇

檔案處理

資料結構

正規表達式

Thread

應用篇

視窗程式

媒體影音

網路程式

遊戲程式

手機程式

資料庫

雲端運算

特殊功能

委派

擴展方法

序列化

LinQ

WPF

網路資源

教學影片

投影片

教學文章

軟體下載

考題解答

101習題

簡介

IP 是 TCP/IP 架構當中代表網址的層次,在撰寫 C# 網路程式時,幾乎每個程式都會用到 IP 層的物件,像是 IPAddress,IPEndPoint 等。我們將在本文當中介紹這些物件的使用方式。

IPAddress 物件代表一個 IP 網址,像是 210.59.154.30 就是一個 IP。在一個大機構當中,由於有自身的內部網路,因此 IP 通常也分為對內與對外兩種。舉例而言,筆者在金門技術學院電腦的內部 IP 是 192.168.60.155,外部 IP 是 210.59.154.30。學校內部的電腦可以透過內部 IP 192.168.60.155 連接到該電腦,但是校外的電腦就只能透過外部 IP 210.59.154.30 連結到該電腦。

但是,IP 畢竟是不好記的數字,因此就發展出了 DNS (Domain Name Server, 網域名稱伺服器) 機制,用來將文字型的網址對應到數字型的 IP,這個文字型的網址稱為 URL (Universial Resource Locator)。

操作實驗

C:\Documents and Settings\ccc.CCC-KMIT2>ipconfig /all

Windows IP Configuration

        Host Name . . . . . . . . . . . . : ccc-kmit3
        Primary Dns Suffix  . . . . . . . :
        Node Type . . . . . . . . . . . . : Mixed
        IP Routing Enabled. . . . . . . . : No
        WINS Proxy Enabled. . . . . . . . : No
        DNS Suffix Search List. . . . . . : internal

Ethernet adapter 區域連線:

        Connection-specific DNS Suffix  . : internal
        Description . . . . . . . . . . . : Broadcom NetLink (TM) Gigabit Ethernet
        Physical Address. . . . . . . . . : 00-01-6C-95-20-52
        Dhcp Enabled. . . . . . . . . . . : Yes
        Autoconfiguration Enabled . . . . : Yes
        IP Address. . . . . . . . . . . . : 192.168.60.155
        Subnet Mask . . . . . . . . . . . : 255.255.255.0
        Default Gateway . . . . . . . . . : 192.168.60.254
        DHCP Server . . . . . . . . . . . : 192.168.1.252
        DNS Servers . . . . . . . . . . . : 10.10.10.3
                                            10.10.10.10
        Primary WINS Server . . . . . . . : 10.10.10.20
        Lease Obtained. . . . . . . . . . : 2010年3月8日 上午 09:45:01
        Lease Expires . . . . . . . . . . : 2012年2月6日 上午 09:45:01

C:\Documents and Settings\ccc.CCC-KMIT2>nslookup ccc.kmit.edu.tw
Server:  ns1.kmit.edu.tw
Address:  10.10.10.3

Name:    ccc.kmit.edu.tw
Address:  192.168.60.155

C:\Documents and Settings\ccc.CCC-KMIT2>nslookup tw.yahoo.com
Server:  ns1.kmit.edu.tw
Address:  10.10.10.3

Non-authoritative answer:
Name:    tw-tpe-fo.fyap.b.yahoo.com
Address:  119.160.246.241
Aliases:  tw.yahoo.com, tw-cidr.fyap.b.yahoo.com

C:\ccc>nslookup
Default Server:  ns1.kmit.edu.tw
Address:  10.10.10.3

> server dns.hinet.net
Default Server:  dns.hinet.net
Address:  168.95.1.1

> ccc.kmit.edu.tw
Server:  dns.hinet.net
Address:  168.95.1.1

Non-authoritative answer:
Name:    ccc.kmit.edu.tw
Address:  203.72.226.32

程式範例

範例一:建立 IPAddress 與 IPEndPoint。

檔案: IPAddressTest.cs

using System;
using System.Net;

class IPAddressTest {
    static void Main() {
        // 建立一個 IP 位址 (IPAddress)。
        IPAddress ipAddr = IPAddress.Parse("210.59.154.30");
        Console.WriteLine("ipAddr="+ipAddr);

        // 建立一個 IP 終端 (IPEndPoint = ipAddress + port)。
        IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 80);
        Console.WriteLine("ipEndPoint=" + ipEndPoint);

        // 將IPEndPoint序列化為SocketAddress
        SocketAddress socketAddr = ipEndPoint.Serialize();
        Console.WriteLine("socketAddr=" + socketAddr);
    }
}

範例一:執行結果:

D:\CSharp>csc IPAddressTest.cs
Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.1
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.

D:\CSharp>IPAddressTest
ipAddr=210.59.154.30
ipEndPoint=210.59.154.30:80
socketAddr=InterNetwork:16:{0,80,210,59,154,30,0,0,0,0,0,0,0,0}

範例二:取得主機名稱

檔案:IpToHost.cs

using System;
using System.Net;
using System.Net.Sockets;

class IpToHost
{
    static void Main(String[] args)
    {
        IPAddress ipAddr = IPAddress.Parse(args[0]);

        // 透過DNS找尋IP位址相對應之主機名稱 
        IPHostEntry remoteHostEntry = Dns.GetHostEntry(ipAddr);

        Console.WriteLine("host of ip " + ipAddr + " is " + remoteHostEntry.HostName);
    }
}

範例二:執行結果:

D:\CSharp>csc IpToHost.cs
Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.1
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.

D:\CSharp>IpToHost 210.59.154.30
host of ip 210.59.154.30 is 210.59.154.30

D:\CSharp>IpToHost 119.160.246.241
host of ip 119.160.246.241 is w1.www.vip.tw1.yahoo.com

範例三:使用 DNS 查詢 IP

檔案:DnsTest.cs

using System;
using System.Net;

class DnsTest
{
    static void Main(String[] args)
    {
        IPHostEntry hostEntry = Dns.GetHostEntry(args[0]);

        // 由於主機有可能有一個以上的 Alias
        // 因此程式中以迴圈方式判斷 Aliases 
        string[] aliasList = hostEntry.Aliases;

        for (int i = 0; i <= aliasList.Length - 1; i++)
        {
         Console.WriteLine("Alias "+i+" : "+aliasList[i]);
        }

        // 由於主機有可能有一個以上的 IP Address
        // 因此程式中以迴圈方式判斷 AddressList 
        IPAddress[] addrList = hostEntry.AddressList;

        for (int i = 0; i <= addrList.Length - 1; i++)
        {
         Console.WriteLine("Address " + i + " : " + addrList[i]);
        }
    }
}

範例三:執行結果

D:\CSharp>DnsTest tw.yahoo.com
Address 0 : 119.160.246.241

範例四:剖析網址 URL

檔案:UrlParseTest.cs

using System;
using System.Net;

class UrlParseTest
{
    static void Main(String[] args)
    {
        // 由於 DOS 的命令列會以 & 符號做命令分隔字元,因此、若以指令模式下,網址中的 & 之後會被視為是下一個指令
        System.Uri URL = new System.Uri("http://findbook.tw/search?keyword_type=keyword&t=xxx");
//        System.Uri URL = new System.Uri(args[0]);
        // System.Uri類別之屬性
        Console.WriteLine("AbsolutePath: " + URL.AbsolutePath);
        Console.WriteLine("AbsoluteUri: " + URL.AbsoluteUri);
        Console.WriteLine("Authority: " + URL.Authority);
        Console.WriteLine("Host: " + URL.Host);
        Console.WriteLine("Port: " + URL.Port);
        Console.WriteLine("LocalPath: " + URL.LocalPath);
        Console.WriteLine("IsDefaultPort: " + URL.IsDefaultPort);
        Console.WriteLine("IsFile: " + URL.IsFile);
        Console.WriteLine("PathAndQuery: " + URL.PathAndQuery);
        Console.WriteLine("Query: " + URL.Query);
        Console.WriteLine("Scheme: " + URL.Scheme);
        Console.WriteLine("UserEscaped: " + URL.UserEscaped);
//        Console.WriteLine("UserInfo: " + URL.UserInfo);
    }
}

範例四:執行結果

C:\ccc>csc UrlParseTest.cs
Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.1
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.

C:\ccc>UrlParseTest
AbsolutePath: /search
AbsoluteUri: http://findbook.tw/search?keyword_type=keyword&t=xxx
Authority: findbook.tw
Host: findbook.tw
Port: 80
LocalPath: /search
IsDefaultPort: True
IsFile: False
PathAndQuery: /search?keyword_type=keyword&t=xxx
Query: ?keyword_type=keyword&t=xxx
Scheme: http
UserEscaped: False

結語

微軟 C# 的 IP 層物件主要是 IPAddress 與 IPEndPoint,另外 IPHostEntry可以用來代表 URL,也可以用 Dns.GetHostEntry() 查詢主機名稱。這些是 C# 較常使用的 IP 層物件。

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License