您的位置:首页 - 教程 - Java - 正文
java端口扫描代码

  项目需要扫描占用的端口来判断服务是否启动,通过查资料发现大多数方法都是ServerSocket socket = new ServerSocket(port);代码如下:

package com.frank.util;  
  
import java.io.IOException;  
import java.net.InetAddress;  
import java.net.Socket;  
import java.net.UnknownHostException;  
  
public class NetUtil {  
      
    /*** 
     *  true:already in using  false:not using  
     * @param port 
     */  
    public static boolean isLoclePortUsing(int port){  
        boolean flag = true;  
        try {  
            flag = isPortUsing("127.0.0.1", port);  
        } catch (Exception e) {  
        }  
        return flag;  
    }  
    /*** 
     *  true:already in using  false:not using  
     * @param host 
     * @param port 
     * @throws UnknownHostException  
     */  
    public static boolean isPortUsing(String host,int port) throws UnknownHostException{  
        boolean flag = false;  
        InetAddress theAddress = InetAddress.getByName(host);  
        try {  
            Socket socket = new Socket(theAddress,port);  
            flag = true;  
        } catch (IOException e) {  
              
        }  
        return flag;  
    }  
} 

  经过测试发现如果端口没有占用,此方法的时间消耗比较大,大概在1s左右,如果是循环扫描端口,无疑是无法接受的。

可以用java.net.ServerSocket包的ServerSocket代替Socket去检测端口,方法如下:

  public static boolean isPortUsing(String host,int port) throws UnknownHostException{  
      boolean flag = true;
//      InetAddress theAddress = InetAddress.getByName(host);  
      try {  
//          Socket socket = new Socket(theAddress,port);  
    	  ServerSocket socket = new ServerSocket(port);  
          flag = false;
          socket.close();
      } catch (IOException e) {
            
      }  
      return flag;  
  }  

  对Socket等知识研究较少,如有问题,请大家及时提出,尽快改正,谢谢!


评论: