Java examples on Java Networking
- How do I create a client-server socket communication?
- How do I get MAC address of a host?
- How do I ping a host?
- How do I read / download webpage content?
- How do I get response header from HTTP request?
- How do I get IP address of localhost?
- How do I create a URL object?
- How do I get a localhost hostname?
- How do I convert raw IP address to String?
- How do I create port scanner program?
How do I create port scanner program?
In this example you'll see how to create a simple port scanner program to check the open ports for the specified host name.
package org.kodejava.example.net;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
public class PortScanner {
public static void main(String[] args) throws Exception {
String host = "localhost";
InetAddress inetAddress = InetAddress.getByName(host);
String hostName = inetAddress.getHostName();
for (int port = 0; port <= 65535; port++) {
try {
Socket socket = new Socket(hostName, port);
String text = hostName + " is listening on port " + port;
System.out.println(text);
socket.close();
} catch (IOException e) {
String s = hostName + " is not listening on port " + port;
System.out.println(s);
}
}
}
}