This article mainly introduces the main principles of Java to check whether the local port is occupied, and gives the operation method based on specific examples. Friends who need it can refer to it
Remember when I was writing programs before , once I need to check the occupied status of the port. Although I don't know how, someone does. So I searched for relevant articles online, as follows.
127.0.0.1 represents the local machine
The main principle is:
##
Socket socket = new Socket(Address,port);#address代表主机的IP地址,port代表端口号
/** * @author MrBread * @date 2017年6月18日 * @time 下午3:14:05 * @project_name TestSocket * 功能:检测本机端口是否已经被使用用 */ package com.mycode.www; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class Main { //start--end是所要检测的端口范围 static int start=0; static int end=1024; public static void main(String args[]){ for(int i=start;i<=end;i++){ System.out.println("查看"+i); if(isLocalPortUsing(i)){ System.out.println("端口 "+i+" 已被使用"); } } } /** * 测试本机端口是否被使用 * @param port * @return */ public static boolean isLocalPortUsing(int port){ boolean flag = true; try { //如果该端口还在使用则返回true,否则返回false,127.0.0.1代表本机 flag = isPortUsing("127.0.0.1", port); } catch (Exception e) { } return flag; } /*** * 测试主机Host的port端口是否被使用 * @param host * @param port * @throws UnknownHostException */ public static boolean isPortUsing(String host,int port) throws UnknownHostException{ boolean flag = false; InetAddress Address = InetAddress.getByName(host); try { Socket socket = new Socket(Address,port); //建立一个Socket连接 flag = true; } catch (IOException e) { } return flag; } }
查看0 查看1 查看2 查看3 查看4 查看5 查看6 查看7 查看8
The above is the detailed content of Detailed example of Java implementation to check whether the local port is occupied source code. For more information, please follow other related articles on the PHP Chinese website!