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地址的主机名
下面一个简单的例子展示这些方法的使用:
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);elseSystem.out.print(256 + b);System.out.print(" ");}}}ip: 65.55.12.249host: www.microsoft.comcanonical host name: wwwco2vip.microsoft.com65 55 12 249
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));}}import java.io.IOException;import java.net.InetSocketAddress;import java.net.Socket;import java.net.UnknownHostException; public class CommonsTelnetTest { public static void main(String [] args){ // TODO Auto-generated method stub Socket server = null; try { server = new Socket(); InetSocketAddress address = new InetSocketAddress("smtp.126.com",25); 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();} }}