Implement port scanner using Java

Source: Internet
Author: User

Text/figure Tian Ming (Ansty)
Last time we wrote a "last modified time editor of the file" in Java, we now use Java to write the port scanner. In order to facilitate and avoid the trouble of GUI programming, we can directly create a tool under the command line, use parameters to start it, and name it "Java simple port scanning tool ". This article only provides the idea of writing black and soft data in Java. Many algorithm optimization and function appending are not discussed in this article, and they use a single thread. Program Interface 1.

Figure 1
We know that using the java.net. Socket class to establish a socket connection will throw an IOException if the connection cannot be established with the specified IP address and port. We use try-catch to capture this IOException to determine whether the connection is successful with the specified IP port. If a connection is established successfully, the specified port of the specified IP address is opened. If an IOException is thrown by the program, the specified port is not opened. Scanning a specified port segment uses a loop to continuously connect to the specified port of the server for us to determine whether the port is open.
I have always believed that as long as there is a clear Algorithm for all problems in the world, it will certainly be implemented in programming languages, no matter what language! Now that we have a principle, we have an algorithm. What else do you mean we have in addition to technology? It's just missing hands!
Because we need to obtain the server address, start port, and end port information from the program startup parameters, we need to use the following code.

Ip = args [0]; // obtain the server address we specified
StartPort = Integer. parseInt (args [1]);
// Obtain the starting port number. Because args [] is of the String type, it must be forcibly converted to the int type.
EndPort = Integer. parseInt (args [2]);
// Obtain the ending port number, same as above

Before obtaining the port and establishing the socket, you must determine the port validity, because the port range is 1 ~ 65535. If we establish a connection to an out-of-range port, it is unnecessary and it is not feasible. Since it is the start port and the end port, there must be a size order problem, that is, to determine their size.

If (startPort <1 | startPort> 65535 | endPort <1 | endPort> 65535 ){
// Check whether the port is in the valid range of 1 ~ 65535
System. out. printf ("the port range must be 1 ~ Less than 65535! ");
Return;
} Else if (startPort> endPort) {// compare the Start port and end Port
System. out. println ("port input error! The starting port must be smaller than the ending port ");
Return;
}

The java.net. Socket class is required to establish a connection with the specified port on the server. First, let's take a look at its construction method.
Socket (): creates an unconnected Socket through SocketImpl of the default system type.
Socket (InetAddress address, int port): Creates a stream Socket and connects it to the specified port number of the specified IP address.
Socket (InetAddress address, int port, InetAddress localAddr, int localPort): Creates a Socket and connects it to the specified remote address on the specified remote port.
Socket (Proxy proxy): creates an unconnected Socket based on the specified Proxy type (if any) that should be used regardless of other settings.
Socket (SocketImpl impl): creates an unconnected Socket with SocketImpl specified by the user.
Socket (String host, int port): Creates a stream Socket and connects it to the specified port number on the specified host.
Socket (String host, int port, InetAddress localAddr, int localPort): Creates a Socket and connects it to the specified remote port on the specified remote host.
We can see that there are many constructor methods. Currently, we only need to care about the second constructor Socket (InetAddress address, int port), because we do not need to interact with services running on ports on the server, therefore, we only need to establish a connection and close the connection. That is, "Socket s = new Socket (address, port );".
Before establishing a connection, we must first convert the IP address to the InetAddress type, not to say that the String type is not available, but to reduce the possibility of more exceptions.
"Static InetAddress getByName (String host)" is used to determine the IP address of the host when the host name is specified. This is a static method. We can just use InetAddress. getByName.

Try {
InetAddress address = InetAddress. getByName (ip );
// Conversion Type
} Catch (UnknownHostException e ){
System. out. println ("cannot be found" + ip );
Return;
}

The following is our core algorithm. Loop all ports in the specified port segment to establish connections to all ports. After the connection is successful, we complete the current loop task and call the close () method to close the connection. Because when "Socket s = new Socket (address, nport)" is executed, if the connection is established successfully, it will not be executed in the catch, but will be executed in the following "result. add ("" + nport) "statement; if it cannot be connected, an exception will be thrown and caught, and the program will run in the catch to execute the statements in the catch; finally, continue to the next loop.

For (int nport = startPort; nport <= endPort; nport ++ ){
// Loop from the starting port to the ending Port
Try {
System. out. print ("Scanning" + nport); // print the Scan progress
Socket s = new Socket (address, nport); // establish a connection
S. close (); // close the connection
Result. add ("" + nport );
// Add the opened port to the ArrayList result
System. out. println (": open"); // print the status
} Catch (IOException e ){
System. out. println (": close"); // print the status
}
}

When printing the final result, we use ArrayList to store the scan result. Because Java does not have pointers in the C language, we need to use ListIterator when accessing the elements in the ArrayList.

ListIterator li = result. listIterator ();
// Obtain the ListIterator of ArrayList
While (li. hasNext () {// if there is an element in li
System. out. println (li. next (). toString () + "Open ");
// Print the pointing element and point it to the next element
}

Now we have introduced the program code for the main functions. I believe that after reading the code, you can also use Java to write your own Java version of the Black soft. As I mentioned earlier, this article provides only one idea. If you are interested, you can implement multithreading on the basis of this article, expand some useful functions, make the GUI interface, or make it more powerful to simulate SuperScan.

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.