检查正在使用的端口

编程入门 行业动态 更新时间:2024-10-28 08:26:20
本文介绍了检查正在使用的端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何检查在哪个端口上运行了某个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.

更多推荐

检查正在使用的端口

本文发布于:2023-10-18 05:59:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1503338.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:端口

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!