[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地址的主机名

  下面一个简单的例子展示这些方法的使用:

 

  
  
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   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值