Java port Scan (original)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.