在我们运行一些项目的时候经常会出现端口占用的情况,那么我们如何检测当前的端口是否已经被占用了呢?
代码如下
import java.net.*;
import java.io.*;public class Main {public static void main(String[] args) {Socket Skt;String host = "localhost";if (args.length > 0) {host = args[0];}for (int i = 0; i < 1024; i++) {try {System.out.println("查看 "+ i);Skt = new Socket(host, i);System.out.println("端口 " + i + " 已被使用");}catch (UnknownHostException e) {System.out.println("Exception occured"+ e);break;}catch (IOException e) {}}}
}
结果输出
……
查看 17
查看 18
查看 19 已被使用
查看 20
查看 21
端口 21 已被使用
查看 22
查看 23
查看 24
……
指定主机的端口
代码如下
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;public class Main {public static void main(String[] args) {// 检测本地 80 端口log(isSocketAliveUitlitybyCrunchify("localhost", 80));// 检测本地 8080 端口log(isSocketAliveUitlitybyCrunchify("localhost", 8080));// 检测本地 8081 端口log(isSocketAliveUitlitybyCrunchify("localhost", 8081));// 检测 runoob.com 的 80 端口log(isSocketAliveUitlitybyCrunchify("runoob.com", 80));// 检测 runoob.com 的 443 端口log(isSocketAliveUitlitybyCrunchify("runoob.com", 443));// 检测 runoob.com 的 81 端口log(isSocketAliveUitlitybyCrunchify("runoob.com", 81));}/*** 判断主机端口* * @param hostName* @param port* @return boolean - true/false*/public static boolean isSocketAliveUitlitybyCrunchify(String hostName, int port) {boolean isAlive = false;// 创建一个套接字SocketAddress socketAddress = new InetSocketAddress(hostName, port);Socket socket = new Socket();// 超时设置,单位毫秒int timeout = 2000;log("hostName: " + hostName + ", port: " + port);try {socket.connect(socketAddress, timeout);socket.close();isAlive = true;} catch (SocketTimeoutException exception) {System.out.println("SocketTimeoutException " + hostName + ":" + port + ". " + exception.getMessage());} catch (IOException exception) {System.out.println("IOException - Unable to connect to " + hostName + ":" + port + ". " + exception.getMessage());}return isAlive;}private static void log(String string) {System.out.println(string);}private static void log(boolean isAlive) {System.out.println("是否真正在使用: " + isAlive + "\n");}}
结果输出
hostName: localhost, port: 80
IOException - Unable to connect to localhost:80. Connection refused
是否真正在使用: truehostName: localhost, port: 8080
IOException - Unable to connect to localhost:8080. Connection refused
是否真正在使用: falsehostName: localhost, port: 8081
IOException - Unable to connect to localhost:8081. Connection refused
是否真正在使用: falsehostName: runoob.com, port: 80
是否真正在使用: truehostName: runoob.com, port: 443
是否真正在使用: truehostName: runoob.com, port: 81
SocketTimeoutException runoob.com:81. connect timed out
是否真正在使用: false