Java 无法获取端口上的服务详细信息?

Java 无法获取端口上的服务详细信息?,java,Java,我希望获取端口中正在使用的服务名称。但是,我不能。我想做的是检查是否使用了端口。如果使用了它,那么我想获取该端口上的服务详细信息。我怎样才能做到这一点,我做错了什么 public int checkPort(int port){ try { InetAddress inetAddress = InetAddress.getLocalHost(); ss = new Socket(inetAddress.getHostAddress(), port);

我希望获取端口中正在使用的服务名称。但是,我不能。我想做的是检查是否使用了端口。如果使用了它,那么我想获取该端口上的服务详细信息。我怎样才能做到这一点,我做错了什么

public int checkPort(int port){
    try {
        InetAddress inetAddress = InetAddress.getLocalHost();
        ss = new Socket(inetAddress.getHostAddress(), port);
        if(ss.isBound()) {
            System.out.println("Port " + port + " is being used by ");
            
            Process p1 = Runtime.getRuntime().exec("grep -w " + port + " /etc/services");
            p1.waitFor();
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
            String line = reader.readLine();
            while(line != null) {
                System.out.println(line);
                line = reader.readLine();
            }
        }
        ss.close();
    } catch (Exception e) {
        System.out.println("Port " +port+ " is not being used");
    }
    return 0;
}
导致

端口139正在被使用

端口139未被使用


好吧,假设您在Windows上(在其他操作系统上可能不同,也可能不同),您可能会遇到此异常

无法运行程序“grep”:CreateProcess错误=2,系统找不到指定的文件

至少,这是我得到的。你可能会得到一个完全不同的错误。这里的主要问题是,有一个很大的try-catch块没有
e.printStackTrace()
,它捕获每个异常。这意味着当它出错时,没有办法知道原因

希望这对你有用。具有讽刺意味的是,您不需要套接字来测试端口上的服务,因此这可能是一个错误

我在端口上查找服务的解决方案如下

socketster.java

package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;

/**
 * An answer for <a href="https://stackoverflow.com/questions/51123167/unable-to-get-service-details-on-port">Unable to get service details on port?</a>
 * 
 * @see <a href="https://stackoverflow.com/questions/51123167/unable-to-get-service-details-on-port">Unable to get service details on port?</a>
 * @version 1.0
 * @author Dan
 */

public class SocketTester {
    /**
     * This method checks whether a port is being used by any services.
     * It will output any information to the system console.
     * 
     * @param port The port to be checked for any services
     */
    public static void checkPort(int port) {
        TreeSet<String> pids = null;
        List<Service> services = null;

        pids = getPIDs(port);

        if(pids != null) {
            services = getServices(port, pids);
        }

        listInformation(port, services);
    }

    /**
     * This method checks whether there are any PIDs on the specified port.
     * If there are these are then returned.
     * 
     * @param port The port to check for PIDs
     * @return It returns a TreeSet containing any found PIDs on the specified port
     */
    private static TreeSet<String> getPIDs(int port) {
        TreeSet<String> returnVal = new TreeSet<String>();

        ProcessBuilder pidProcessBuilder = new ProcessBuilder("cmd.exe", "/C", "netstat -ano | find \"" + port + "\"");
        pidProcessBuilder.redirectErrorStream(true);

        Process pidProcess = null;
        try {
            pidProcess = pidProcessBuilder.start();
        } catch (IOException e) {
            return null;
        }

        BufferedReader pidProcessOutputReader = new BufferedReader(new InputStreamReader(pidProcess.getInputStream()));
        String outputLine = null;

        try {
            outputLine = pidProcessOutputReader.readLine();
        } catch (IOException e) {
            return null;
        }

        while (outputLine != null) {
            List<String> outputLineParts = new ArrayList<String>(Arrays.asList(outputLine.split(" ")));
            outputLineParts.removeAll(Arrays.asList(""));

            //outputLineParts.get(1) is the local address. We don't want a foreign address to accidently be found
            //outputLineParts.size() - 1 is the PID
            if(outputLineParts.get(1).contains(":" + port) && !returnVal.contains(outputLineParts.get(outputLineParts.size() - 1))) {
                returnVal.add(outputLineParts.get(outputLineParts.size() - 1));
            }

            try {
                outputLine = pidProcessOutputReader.readLine();
            } catch (IOException e) {
                return null;
            }
        }

        try {
            pidProcess.waitFor();
        } catch (InterruptedException e) {
            return null;
        }

        return returnVal;
    }

    /**
     * This method checks whether there are any services related to the PID.
     * If there are these are then returned.
     * 
     * @param port A reference to the PIDs port
     * @param pids A list of PIDs found by getPIDs
     * @return It returns a List containing any found services on the specified PIDs
     */
    private static List<Service> getServices(int port, TreeSet<String> pids) {
        List<Service> returnVal = new ArrayList<Service>();

        for(String pid : pids) {
            ProcessBuilder serviceProcessBuilder = new ProcessBuilder("cmd.exe", "/C", "tasklist /svc /FI \"PID eq " + pid + "\" | find \"" + pid + "\"");
            serviceProcessBuilder.redirectErrorStream(true);

            Process serviceProcess = null;
            try {
                serviceProcess = serviceProcessBuilder.start();
            } catch (IOException e) {
                return null;
            }

            BufferedReader serviceProcessOutputReader = new BufferedReader(new InputStreamReader(serviceProcess.getInputStream()));
            String outputLine = null;

            try {
                outputLine = serviceProcessOutputReader.readLine();
            } catch (IOException e) {
                return null;
            }

            while(outputLine != null) {
                List<String> outputLineParts = new ArrayList<String>(Arrays.asList(outputLine.split(" ")));
                outputLineParts.removeAll(Arrays.asList(""));

                //outputLineParts.get(0) is the service
                returnVal.add(new Service(port, pid, outputLineParts.get(0)));

                try {
                    outputLine = serviceProcessOutputReader.readLine();
                } catch (IOException e) {
                    return null;
                }
            }

            try {
                serviceProcess.waitFor();
            } catch (InterruptedException e) {
                return null;
            }
        }
        return returnVal;
    }

    /**
     * This method lists the information found by checkPort
     * 
     * @param port The port that has been checked for services
     * @param servicesRunning The services found on the port
     */
    private static void listInformation(int port, List<Service> servicesRunning) {
        if(servicesRunning != null && servicesRunning.size() != 0) {
            System.out.println("The following services are being run on port " + port);
            for(Service service : servicesRunning) {
                System.out.println("\t" + service.getService());
            }
        } else {
            System.out.println("There are no services being run on port " + port);
        }
    }

    public static void main(String[] args) {
        final int portToCheck = 135;
        checkPort(portToCheck);
    }
}
package socket;

/**
 * An supplementary class to support SocketTester
 * 
 * @see <a href="https://stackoverflow.com/questions/51123167/unable-to-get-service-details-on-port">Unable to get service details on port?</a>
 * @version 1.0
 * @author Dan
 */

public class Service {
    private int port;
    private String pid;
    private String service;

    public Service(int port, String pid, String service) {
        this.port = port;
        this.pid = pid;
        this.service = service;
    }

    public int getPort() {
        return port;
    }

    public String getPID() {
        return pid;
    }

    public String getService() {
        return service;
    }

    @Override
    public String toString() {
        return "Service \"" + "\" is being run on port " + port + " and has the PID " + pid;
    }
}
封装插座;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入java.util.array;
导入java.util.List;
导入java.util.TreeSet;
/**
*答案
* 
*@见
*@version 1.0
*@作者丹
*/
公务舱短袜{
/**
*此方法检查端口是否正在被任何服务使用。
*它将向系统控制台输出任何信息。
* 
*@param port要检查任何服务的端口
*/
公共静态无效检查端口(int端口){
TreeSet-pids=null;
列表服务=null;
pids=getPIDs(端口);
如果(PID!=null){
服务=获取服务(端口、pids);
}
列表信息(港口、服务);
}
/**
*此方法检查指定端口上是否存在任何PID。
*如果有,则返回。
* 
*@param port用于检查PID的端口
*@return返回一个树集,其中包含在指定端口上找到的任何PID
*/
专用静态树集getPIDs(int端口){
TreeSet returnVal=新树集();
ProcessBuilder pidProcessBuilder=newProcessBuilder(“cmd.exe”、“/C”、“netstat-ano | find\”“+port+”);
pidProcessBuilder.redirectErrorStream(true);
进程pidProcess=null;
试一试{
pidProcess=pidProcessBuilder.start();
}捕获(IOE异常){
返回null;
}
BufferedReader pidProcessOutputReader=新的BufferedReader(新的InputStreamReader(pidProcess.getInputStream());
字符串outputLine=null;
试一试{
outputLine=pidProcessOutputReader.readLine();
}捕获(IOE异常){
返回null;
}
while(outputLine!=null){
List outputLineParts=newarraylist(Arrays.asList(outputLine.split(“”));
outputLineParts.removeAll(Arrays.asList(“”));
//outputLineParts.get(1)是本地地址。我们不希望意外找到外部地址
//outputLineParts.size()-1是PID
if(outputLineParts.get(1).contains(“:”+端口)和&!returnVal.contains(outputLineParts.get(outputLineParts.size()-1))){
returnVal.add(outputLineParts.get(outputLineParts.size()-1));
}
试一试{
outputLine=pidProcessOutputReader.readLine();
}捕获(IOE异常){
返回null;
}
}
试一试{
pidProcess.waitFor();
}捕捉(中断异常e){
返回null;
}
返回值;
}
/**
*此方法检查是否存在与PID相关的任何服务。
*如果有,则返回。
* 
*@param port对PIDs端口的引用
*@param pids getPIDs找到的pids列表
*@return返回一个列表,其中包含在指定PID上找到的任何服务
*/
私有静态列表getServices(int端口、TreeSet pids){
List returnVal=new ArrayList();
用于(字符串pid:pid){
ProcessBuilder serviceProcessBuilder=new ProcessBuilder(“cmd.exe”、“/C”、“任务列表/svc/FI\”PID eq“+PID+”\”;find\”+PID+“\”);
serviceProcessBuilder.redirectErrorStream(true);
processserviceprocess=null;
试一试{
serviceProcess=serviceProcessBuilder.start();
}捕获(IOE异常){
返回null;
}
BufferedReader serviceProcessOutputReader=新的BufferedReader(新的InputStreamReader(serviceProcess.getInputStream());
字符串outputLine=null;
试一试{
outputLine=serviceProcessOutputReader.readLine();
}捕获(IOE异常){
返回null;
}
while(outputLine!=null){
List outputLineParts=newarraylist(Arrays.asList(outputLine.split(“”));
outputLineParts.removeAll(Arrays.asList(“”));
//outputLineParts.get(0)是服务
returnVal.add(新服务(端口、pid、outputLineParts.get(0));
试一试{
outputLine=serviceProcessOutputReader.readLine();
}捕获(IOE异常){
返回null;
}
}
试一试{
serviceProcess.waitFor();
}捕捉(中断异常e){
返回null;
}
}
返回值;
}
/**
*此方法列出checkPort找到的信息
* 
*@param port已检查服务的端口
*@param services运行在端口上找到的服务