The project needs to scan the ports used to determine if the service is started, and by looking at the data it finds that most of the methods are serversocket socket = new ServerSocket (port) and the code is as follows:
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 with using false:not using * @param port */Pub Lic 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 Unknownho Stexception */public static Boolean isportusing (String host,int port) throws unknownhostexception{Bo Olean flag = false; InetAddress theaddress = inetaddress.getbyname (host); try {Socket socket = new socket (theaddress,port); Flag = true; } catch (IOException e) {} return flag; } }
After testing that if the port is not occupied, the time consumption of this method is relatively large, about 1s, if it is a circular scan port, is undoubtedly unacceptable.
You can use the Java.net.ServerSocket packet serversocket instead of the socket to detect the port, the method is as follows:
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 and other knowledge less, if there are problems, please put forward, as soon as possible to correct, thank you!
Java port Scan (original)