java--網路編程-基礎知識

來源:互聯網
上載者:User

標籤:

java為網路支援提供了java.net包,該包下的URL和URLConnection等類提供了以編程方式訪問Web服務的功能,而URLDecoder和URLEncoder則提供了一般字元串和appliction/x-www-form-urlencoded MIME 字串相互轉換的靜態方法。

使用InetAddress類(實現的介面是Serializable序列化介面):

java提供了InetAddress類代表IP地址,InetAddress下還有兩個子類:Inet4Address、Inet6Address,他們分別代表IPv4和IPv6地址。

InetAddress沒有提供構造器,而是提供了如下兩個靜態方法來擷取InetAddress執行個體。

1、getByName(String host):根據主機擷取對應的InetAddress對象。

2、getByAddress(byte[] addr):根據原始IP地址來擷取對應的InetAddress對象。

 

static InetAddress[] getAllByName(String host) 
          在給定主機名稱的情況下,根據系統上配置的名稱服務返回其 IP 位址所組成的數組。
static InetAddress getByAddress(byte[] addr) 
          在給定原始 IP 位址的情況下,返回 InetAddress 對象。
static InetAddress getByAddress(String host, byte[] addr) 
          根據提供的主機名稱和 IP 位址建立 InetAddress。
static InetAddress getByName(String host) 
          在給定主機名稱的情況下確定主機的 IP 位址。

 

InetAddress還提供了如下三個方法來擷取InetAddress執行個體對應的IP地址和主機名稱。

1、String getCanonicalHostName():擷取此IP地址的全限定網域名稱。

2、String getHostAddress():返回該InetAddress執行個體對應的IP地址字串(以字串形式).

3、String getHostName():擷取此IP地址的主機名稱。

除此之外,InetAddress類還提供了一個getLocalHost()方法來擷取本機IP地址對應的InetAddress執行個體。

InetAddress類還提供了一個isReachable()方法,用於測試是否可以到達該地址,該方法將盡最大努力試圖到達主機。

 

 1 import java.net.InetAddress; 2 public class InetAddressClass 3 { 4     public static void main(String[] arg) throws Exception{ 5         //根據主機名稱來擷取對應的InetAddress執行個體 6         InetAddress ip=InetAddress.getByName("www.baidu.com"); 7         //判斷是否可到達 8         System.out.println("baidu是否可達到:"+ip.isReachable(2000)); 9         //獲得該InetAddress執行個體的IP字串10         System.out.println(ip.getHostAddress());11         //根據原始IP地址來擷取對應的InetAddress執行個體12         InetAddress local=InetAddress.getByAddress(new byte[]{127,0,0,1});13         //判斷主機是否可到達14         System.out.println("本機主機是否可以到達:"+local.isReachable(2000));15         //擷取該InetAddress執行個體對用的全限定網域名稱16         System.out.println(local.getCanonicalHostName());17     }18 }

 

java--網路編程-基礎知識

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.