Learning Java in 2020 – Beginner – Available Ports in a Machine ( Network Programming Basics)

Overview reference

Problem

Goal

Try to find open ports on a computer by using its ip address..

Pseudo-code

  1. Get the ip address
  2. Get range of ports to be checked
  3. Make connections to ip address at each port within the given range
  4. If connection is established, write the port in the “openports.txt” file and close the connection

Theoretical Background: Network programming

Most applications installed in our computer are involved in some network communication, to either pull data or send information somewhere else. For example, skype for video conferences, google chrome for connecting to a website hosted on another ( or remote) computer, microsoft word which has a “bibliography” feature that pulls related articles from a database e.g. Pubmed, etc. This is why I decided to read about this subject in detail even though I may never need to know so much low level information in practice due to existing libraries or/and modules that do the work for us already.

Network

You have probably seen this word a lot on LinkedIn. So I like to visualize it as a bunch of computers in a room all connected over a wire. Information e.g. text messages can be sent physically ( e.g. over the wire) or wireless over radio waves ( do not ask me!! I saw this somewhere). It really doesn’t always have to be a typical computer/laptop/pc; it could be a room with 1 laptop physically connected to a gaming PC which is also physically connected to some HP printer. And the printer could be wireless connected to an Iphone. All these devices are under a network.

Network Node

Each device, node, has a name or an address assigned to it based on the network it is affiliated with. Another visual; imagine you had a new name for every country you visited and that name isn’t defined by you, but by the government of the country. So in an internet network, you or your laptop/samsung galaxy phone, a node, was given a name by your internet service provider. There is apparently a bigger organization that manages the creation and assignment of ip addresses.

This website you are reading right now is being hosted on some computer that I “rent”. That computer or node also has a name or internet address. Some networks assign human readable text names to an address e.g www.ajalacomfort.com.

Network packets

Information transmitted/sent between nodes is called data. This data is or can be broken up into smaller chunks called packets. So how does the split data get re-assembled ? How does the receiver node know how to build it back? Good question. There are set of rules called “protocols” which provide information on how the data was split, how to translate the addresses or name. Protocols are like alphabets and grammar principles to the english language or hangul to korean. This means, an acer laptop can communicate with a refrigerator only if it speaks its own protocol (“language”).

Sockets

Based on my understanding, sockets are tiny doors that allow for communication between services/applications in a machine ( e.g. computer) or between one machine and another. The languages by which communication is established are termed protocols. Depending on the protocol, the information transferred during a communication, packet, could be sent with extreme caution ( TCP) or in a relatively unmonitored manner (UDP). A socket is identified by the combination of the computer’s address ( within a network e.g. localhost) and a port of the computer, host machine.

So from the minimal understanding I have up until this point is: In order for my laptop to connect to a “listen with me” music streaming software on my friends computer, first my computer needs to be a part of my friend’s computer’s network. Then I need her IP address and she needs to know mine, so she can be sure that she isn’t listening to her fav playlist with some stranger. Then I need to know the port where the software is running. Since there are so many services running on her laptop at their corresponding ports, I need to target the desired software. Finally I connect.

Solution

Get IP address

private void getUserInput(){
		System.out.println("Type in IP Address: ");
		Scanner sc = new Scanner(System.in);
		String ip = sc.nextLine();
		this.ipaddress = ip;
		System.out.println("Type in minimum port value: ");
		String min = sc.nextLine();
		if(min.length() > 0) {
			this.min  = Integer.parseInt(min);	
		}
		System.out.println("Type in maximum port value: ");
		String max = sc.nextLine();
		if(max.length() > 0) {
			this.max = Integer.parseInt(max);
		}
		
	}

Make connection to port @ IP address

By creating an instance of the Socket class with an IP address and port as arguments, you are making a connection to the port at that ip address. The socket generated is a stream socket (TCP).

private void connectMachine(String ipaddress, int port)  {
		try {
			Socket socket = new Socket(ipaddress, port);
			System.out.println(String.format("PORT %s:%d is OPEN ",ipaddress,port));
			this.writeInFile(String.format("%s:%d%n", ipaddress, port));
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			
			System.out.println(String.format("PORT %s:%d is either Closed or does not EXIST ",ipaddress, port));
		}
		
	}

Reasons for Exceptions

The port is already in use by another application – BindException

The port does not exist on that machine – NullPointerException

The port has an extra level of security – SecurityException

You probably passed a weird/invalid argument – IllegalArgumentException

Thus if a connection is established without an exception thrown, then voila, we can assume the port exists and is open! Yea! ( please correct me if I am wrong)

Write open port to file

private void writeInFile(String message) {
		File file = new File("openports.txt");
		try {
			FileWriter filewriter = new FileWriter(file, true);
			filewriter.write(message);
			filewriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

Author Notes

This is most likely not the cleanest implementation, just a heads up.

Links

  1. Python Solution:
  2. socket programming java – Connect to a machine
  3. Java Net Connection Timeout Error
  4. How to get your local IP address
  5. String to Int
  6. Java write to file
  7. Creating new line with filewriter
  8. Computer Network Programming
  9. Comprehensive overview of network programming in C
  10. O’reilly’s Basic Network concepts