I Im writing a port scanner in java as an educational exercise and I have run into a problem.
My program works fine when im scanning the ports on my local machine, however when i try to scan for ports on foriegn computers the process just freezes. Here is the code for my scan method:
public void scan(InetAddress ad, int start, int end){
for(int i=start; i<=end; i++){
try{
socket = new Socket(ad, i);
System.out.println("Port "+i+"is open");
}catch(Exception e){
System.out.println("Port "+i+"is not open");
}
}
}
So far it is working when the host name is my loopback address or just “localhost”, it even works with my IP Address. But when I for instance resolve the IP for http://www.google.com or even give it the IP address of my other computer on the same network, the program will freeze after scanning the first port.
I am resolving the IP address like this:
inetAddressObject = InetAddress.getByName(hostNameString);
Can anyone tell me if I am missing a big difference between scanning ports on a local machine and scanning ports on a foreign host? Or is there just something simple going wrong with my code ?
The way you are calling the Socket constructor the connection will be made right away. The problem is that if the connection times out then you will have to wait a while (OS default). The way you should do it is the following:
The separate reason is why it is timing out. This is because your machine is likely behind a firewall of some sorts and is unrelated to your code example.