java查找端口冲突、根据端口查找进程pid

package top.malaoshi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class FindPort {

    static void print(InputStream is) throws IOException{
        InputStreamReader isr=new InputStreamReader(is);
        BufferedReader br=new BufferedReader(isr);
        String line="";
        while( (line=br.readLine())!=null ){
            System.out.println(line);
        }
    }

    /**
     * windows系统
     * @param port
     * @throws IOException 
     */
    static void processWin(int port) throws IOException{
        String command = "cmd /C netstat -ano | findstr "+port;
        Process p=Runtime.getRuntime().exec(command);
        InputStream is=p.getInputStream();
        InputStream es=p.getErrorStream();

        InputStreamReader isr=new InputStreamReader(is);
        BufferedReader br=new BufferedReader(isr);

        //获取返回的字符串,并解析出占用端口号的进程id
        Set<String> pids=new HashSet<>();

        String line="";
        while( (line=br.readLine())!=null ){
            String[] array=line.trim().split("\\s+");
            String pid=array[array.length-1];
            if(array.length>=2){
                int pos=array[1].indexOf(":");
                String portOfLine=array[1].substring(pos+1).trim();
                //会出现多个相同的pid,绑定同一个端口号,这种情况只打印一次pid
                if(portOfLine.equals(port+"") && !pids.contains(pid)){
                    String name=getNameByPIDWin(pid);
                    System.out.println("  "+pid+"\t"+name+"\t"+array[0]);
                    pids.add(pid);//将pid放入到set中
                }

            }
        }
        //打印错误
        print(es);


        is.close();
        es.close();
    }

    /**
     * windows系统
     * @param port
     * @throws IOException 
     */
    static void processLinux(int port) throws IOException{
        String command = "netstat -tlnp | grep "+port;
        Process p=Runtime.getRuntime().exec(new String[]{"sh", "-c", command});
        InputStream is=p.getInputStream();
        InputStream es=p.getErrorStream();

        InputStreamReader isr=new InputStreamReader(is);
        BufferedReader br=new BufferedReader(isr);

        //获取返回的字符串,并解析出占用端口号的进程id
        Set<String> pids=new HashSet<>();

        String line="";
        while( (line=br.readLine())!=null ){
//            System.out.println("line:::"+line);
            String[] array=line.trim().split("\\s+");
//            System.out.println("---------");
//            for(String item:array){
//                System.out.println(item);
//            }
//            System.out.println("---------");

            String ipAndPort=array[3];
            String pidAndName=array[array.length-1];
            String[] pidAndNames=pidAndName.split("/");
            String pid=pidAndNames[0];
            String name=pidAndNames[1];

//            System.out.println("pid:"+pid);
//            System.out.println("ipAndPort:"+ipAndPort);
//            System.out.println("name:"+name);
//            System.out.println("port:"+port);
//            System.out.println("array.length:"+array.length);

            if(array.length>=3){
                int pos=ipAndPort.indexOf(":");
                String portOfLine=ipAndPort.substring(pos+1).trim();
//                System.out.println("portOfLine:"+portOfLine);
                //会出现多个相同的pid,绑定同一个端口号,这种情况只打印一次pid
                if(portOfLine.equals(port+"") && !pids.contains(pid)){
                    System.out.println("  "+pid+"\t"+name+"\t"+array[0]);
                    pids.add(pid);//将pid放入到set中
                }

            }
        }
        //打印错误
        print(es);


        is.close();
        es.close();
    }
    /**
     * 根据pid获取进程名
     * @param pid
     * @return
     * @throws IOException
     */
    static String getNameByPIDWin(String pid) throws IOException{
        String res="";

        String command = "cmd /C tasklist|findstr "+pid;
        Process p=Runtime.getRuntime().exec(command);
        InputStream is=p.getInputStream();
        InputStream es=p.getErrorStream();

        InputStreamReader isr=new InputStreamReader(is);
        BufferedReader br=new BufferedReader(isr);


        String line="";
        while( (line=br.readLine())!=null ){
            String[] array=line.trim().split("\\s+");
            if(array.length>=2){
                String pidOfLine=array[1];
                if(pidOfLine.equals(pid) ){
                    res=array[0];
                    break;
                }

            }
        }
        //打印错误
        print(es);
        is.close();
        es.close();
        return res;
    }
    static void run() throws IOException{
        String os = System.getProperty("os.name");  
        System.out.print("请输入端口号:");

        Scanner scan=new Scanner(System.in);
        int port=0;
        while(true){
            try{
                String portStr=scan.nextLine();
                port=Integer.parseInt(portStr);
                break;
            }catch(Exception e){
                System.out.print("请输入正确的端口号:");
            }
        }
        System.out.println("占用 ["+port+"] 端口的 PID 是:");
        //为了方便判断,将字母全部改为小写
        os=os.toLowerCase();
        if(os.startsWith("win")){
            processWin(port);
        }else if(os.startsWith("linux")){
            processLinux(port);
        }else{
            System.out.println("不支持该操作系统");
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("本程序根据端口号查找进程号(PID) v0.1");
        String os = System.getProperty("os.name");  
        System.out.println("当前操作系统:"+os);

        System.out.println("");

        while(true){
            try {
                run();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println();
        }
    }

}

原文出处:/show_1IX2iXPXBmsQ.html