How to check if a port number is in use in Java?
To check if a port number is in use, you can use the Socket class in Java to attempt to establish a connection. If the connection is successful, it means the port number is in use; if not, the port number is available. Here is a simple example code:
import java.io.IOException;
import java.net.Socket;
public class PortScanner {
public static void main(String[] args) {
int port = 8080; // 要检测的端口号
String host = "localhost"; // 主机名
try {
Socket socket = new Socket(host, port);
System.out.println("Port " + port + " is already in use");
socket.close();
} catch (IOException e) {
System.out.println("Port " + port + " is available");
}
}
}
In the above code, we attempt to establish a Socket connection on the specified host and port. If the connection is successful, a message indicating that the port is already in use is displayed; otherwise, a message indicating that the port is available is displayed.
Please note that this method can only detect if a port is being used on a specified host. If you need to check if a port is being used on the local machine, you can set the hostname to “localhost” or “127.0.0.1”. If you need to check if a port is being used on a remote machine, you will need to set the hostname to the corresponding IP address.