NETUtil IP是否可达

来源:互联网 发布:阿里云 虚拟主机 编辑:程序博客网 时间:2024/05/02 22:43

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class NetUtil {

/**
  * 判断IP地址是否可到达
  */
public static boolean isReach(String ip) {
  if(ip == null) {
   ip = "";
  }
  boolean iRet = false;
  Runtime runtime = Runtime.getRuntime();
  int timeout = 100;
  String ping = "ping " + ip + " -w " + timeout;
  try {
   Process process = runtime.exec(ping);
   if(process == null) {
    iRet = false;
    System.out.println("IP地址:" + ip + "不可到达!");
    return iRet;
   }
   BufferedReader br = new BufferedReader(new InputStreamReader(
     process.getInputStream()));
   String line = null;
   while((line = br.readLine()) != null) {
    if(line.startsWith("Reply from")) {
     iRet = true;
     System.out.println("IP地址:" + ip + "可到达!");
     break;
    }
   }
   br.close();
  } catch (IOException e) {
   iRet = false;
   e.printStackTrace();
  }
  return iRet;
}

/**
  * 判断端口Port是否有响应
  * @param ip
  * @param port 必须是数字
  * @return
  */
public static boolean portScan(String ip, int port) {
  //判断IP是否可达,不可达直接返回
  if(!isReach(ip)) {
   return false;
  }
  boolean iRet = false;
  Socket socket = null;
  try {
   socket = new Socket(ip, port);
   iRet = true;
  } catch (UnknownHostException e) {
   System.out.println("无法识别主机");
   iRet = false;
  } catch (IOException e) {
   System.out.println("端口未响应");
   iRet = false;
  } finally {
   try {
    if(socket != null) {
     socket.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return iRet;
}
}