java检测linux系统中所有端口的ip地址

本文详细介绍了使用Java代码检测Linux设备所有网口端口占用的方法,并指出忽略DNS端口53可能导致的死锁问题,提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

boolean globFlag = false;
int tempPort = Integer.valueOf(port);
//获取设备所有网口的ip地址
Enumeration allNetInterfaces = null;
        try {        
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();  
        } catch (java.net.SocketException e) {          
            e.printStackTrace();  

        }  

//检测每一个网口上的这个端口是否可以连接上

        InetAddress ip = null; 
        while (allNetInterfaces.hasMoreElements()) {
        NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); 
        Enumeration addresses = netInterface.getInetAddresses();
        while (addresses.hasMoreElements()){
        ip = (InetAddress) addresses.nextElement();
        if(ip!=null && ip instanceof Inet4Address){
        String  ipAddress = ip.getHostAddress();          
        log.error("ip:-------"+ipAddress);          
        try{
        Socket socket = new Socket(ipAddress,tempPort);
        globFlag = true;
        }catch (Exception e) {
// TODO: handle exception
}
        if(globFlag){
        break;
        }
        }
        }
        if(globFlag){
        break;
        }
        }
if(globFlag){
response.setContentType("text/json;charset=UTF-8");
response.getWriter().write(
"{\"success\":"
+ false
+ ",\"msg\":\""
+ "该端口已经被占用" + "\"}");
return null;

}


说明:这种用java的方式去检测linux下的端口 的占用情况存在漏洞,原因就是DNS端口53却没有被检测到,

可以使用 netstat -nap|grep 53 命令去查看,会发现该设备上的所有的网口对应的ip上的端口虽然是没有进程在使用的;

但是该端口是不能作为web服务的端口,因为一旦用web使用该端口号,可以查看到web进程是启动起来的,但是DNS端口就被web占用了,

从而形成死锁,无法访问到web服务。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值