Home >Java >javaTutorial >Detailed example of Java implementation to check whether the local port is occupied source code

Detailed example of Java implementation to check whether the local port is occupied source code

黄舟
黄舟Original
2017-09-14 10:25:021880browse

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代表端口号

If the host is specific If a socket can be established with the port number, it means that the port of the host is in use.


/**
 * @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; 
  } 
}

The output results are as follows:


查看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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn