歡迎您光臨本站 註冊首頁

PING和TELNET用法介紹

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0

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

  InetAddress對象的常用方法

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

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

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

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

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

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

  1 package org.dakiler.javanet.chapter1;

  2   import java.net.InetAddress;

  3   public class Example3

  4   {

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

  6   {

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

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

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

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

  11   byte[] bytes=address.getAddress();

  12   for(byte b:bytes)

  13   {

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

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

  16   System.out.print(" ");

  17   }

  18   }

  19   }

  20

  這個例子首先是獲取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是超時時間.

  一個簡單的例子如下:

  1 package org.dakiler.javanet.chapter1;

  2   import java.net.InetAddress;

  3   public class Example4

  4   {

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

  6   {

  7   InetAddress address1=InetAddress.getLocalHost();

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

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

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

  11   }

  12   }

  13

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

  true

  false

  感覺奇怪么,前者是正常的,但是按理說www.baidu.com應該也是可達的,實際確實false,這個原因是isReachable的實現,

  通常是ICMP ECHO Request 或是嘗試使用目標主機上的埠7進行連接,很有可能被防火牆攔截,會訪問不到.

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

  1 // TODO Auto-generated method stub

  2   Socket server = null;

  3   try {

  4   server = new Socket();

  5   InetSocketAddress address = new InetSocketAddress("bbs.sysu.edu.cn",23);

  6   server.connect(address, 5000);

  7   System.out.println("ok!");

  8   }

  9   catch (UnknownHostException e) {

  10   System.out.println("wrong!");

  11   e.printStackTrace();

  12   } catch (IOException e) {

  13   System.out.println("wrong");

  14   e.printStackTrace();

  15   }


[火星人 ] PING和TELNET用法介紹已經有1170次圍觀

http://coctec.com/docs/java/show-post-60606.html