检查正在使用的端口 [英] Check what ports are being used

查看:203
本文介绍了检查正在使用的端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查在哪个端口上运行了某个IP地址的服务. (请使用Java代码)

How can I check at which ports there is a service running of a certain ip address. ( code in java please)

我的教授问每次程序发现运行中的服务时,它都必须打印该消息".由此,我以为他要我找出正在使用的端口.但是,我只是再次问了他.他告诉我,我只需要检测一个空闲(未使用)的端口即可.

My prof asks "Every time the program discovers a running service it has to print the message". From that, I thought he wants me to find out what ports are being used. However, I just asked him again. And he told me that I just need to detect a a port which is free (not being used).

所以,我想我解决了我的问题. 感谢您的帮助.

So, I think I solve my problem. Thanks for help.

推荐答案

public int getServiceByName(String tcpipService, String tcpipClass) {
    int port = -1;
    try {
        String line;
        BufferedReader br = new BufferedReader(
                    new InputStreamReader(
                       new FileInputStream(
                        "/etc/services")));
        while (((line = br.readLine()) != null)
                && (port == -1)) {
            if ((line.length() != 0)
                    && (line.charAt(0) != '#')) {
                port = parseServicesLine(line,
                    tcpipService, tcpipClass);
            }
        }   
        br.close();
        return (port); 
    } catch (IOException ioe) {
        return -1; 
    }
}   

private int parseServicesLine(String line,
        String tcpipService) {
    StringTokenizer st = new
        StringTokenizer(line, " \t/#");

    if (! st.hasMoreTokens()) {
        return -1; // error
    }
    String name = st.nextToken().trim();

    if (! st.hasMoreTokens()) {
        return -1; // error
    }
    String portValue = st.nextToken().trim();

    // Return port number, if name on this line matches:
    if (name.equals(tcpipService)) {
        try { 
            return (Integer.parseInt(portValue));
        } catch (NumberFormatException nfe) {
            return -1; 
        }
    } else {
        return -1; 
    }
}   

上面的代码片段针对服务名称搜索/etc/inet/services文件,并返回端口号.

The above code snippet searches the /etc/inet/services file against a service-name and returns the port-number.

这篇关于检查正在使用的端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆