JAVA裏的PING和TELNET


JAVA裏的PING是在JDK 1.5後用了新的函數isreachable去實現,具體介紹如下:

InetAddress對象的常用方法

InetAddress類有很多get方法,用來獲取主機名,主機地址等信息。主要有:

byte[] getAddress() 返回次InetAddress對象的原始IP地址,保存爲一個byte數組

String getCanonicalHostName() 獲取此IP地址的完全限定域名

String getHostAddress() 獲取IP地址的字符串,返回爲一個String

String getHostName() 獲取此IP地址的主機名

下面一個簡單的例子展示這些方法的使用:

package org.dakiler.javanet.chapter1;


import java.net.InetAddress;


public class Example3

{

    public static void main(String args[])throws Exception

     {

         InetAddress address=InetAddress.getByName("www.microsoft.com");

         System.out.println("ip: "+address.getHostAddress());

         System.out.println("host: "+address.getHostName());

         System.out.println("canonical host name: "+address.getCanonicalHostName());

        byte[] bytes=address.getAddress();

        for(byte b:bytes)

         {

            if(b>=0)System.out.print(b);

            else System.out.print(256+b);

             System.out.print(" ");

         }

     }

}

這個例子首先是獲取www.microsoft.com的對應的InetAddress實例,然後分別打印address.getHostAddress() address.getHostName()以及address.getCanonicalHostName()。在這個例子中,需要注意的是IP地址中,每一個都是0-255之間的,是無符號的。但是java中的byte表示的區域是-128~127,所以中間需要做一個轉換。

結果如下:

ip: 207.46.19.254

host: www.microsoft.com

canonical host name: wwwbaytest2.microsoft.com

207 46 19 254


1.2. InetAddress對象的其他實用方法

isReachable(int timeout) 測試是否能達到特定IP地址

isReachable(NetworkInterface netif,int ttl,int timeout)測試是否能達到特定IP地址,並且制定特定的NetworkInterface,ttl表示路由過程中的最大跳數,timeout是超時時間。一個簡單的例子如下:

package org.dakiler.javanet.chapter1;


import java.net.InetAddress;


public class Example4

{

    public static void main(String args[])throws Exception

     {

         InetAddress address1=InetAddress.getLocalHost();      

         InetAddress address2=InetAddress.getByName("www.baidu.com");

         System.out.println(address1.isReachable(5000));

         System.out.println(address2.isReachable(5000));

     }

}

分別測試本機是否可達以及www.baidu.com是否可達。運行的結果是:

true

false

感覺奇怪麼,前者是正常的,但是按理說www.baidu.com應該也是可達的,實際確實false,這個原因是因爲isReachable的實現,通常是ICMP ECHO Request 或是嘗試使用目標主機上的端口7進行連接,很有可能被防火牆攔截,所以會訪問不到。

  如果要TELNET的話,會比較準確,比如以下代碼

 // TODO Auto-generated method stub
   Socket server = null;
         try {
             server = new Socket();
             InetSocketAddress address = new InetSocketAddress("bbs.sysu.edu.cn",23);
             server.connect(address, 5000);
              System.out.println("ok!");

 }
         catch (UnknownHostException e) {
           System.out.println("wrong!");
             e.printStackTrace();
         } catch (IOException e) {
          System.out.println("wrong");
             e.printStackTrace();
         }

 

 

發佈了33 篇原創文章 · 獲贊 0 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章