【问题标题】:List Open TCP connections in Java在 Java 中列出打开的 TCP 连接
【发布时间】:2014-07-09 06:23:57
【问题描述】:

我想知道如何列出系统上使用 Java 打开的所有 TCP 连接。我正在使用 CentOS。

我也不知道从哪里开始。任何指针都会有所帮助。

提前致谢

感谢您的提示 我必须做这样的事情

Q) 为当前正在侦听的所有 tcp 端口识别任何新建立的连接
并继续每 5 秒轮询一次。当不再有任何已建立的连接时,脚本应该终止。

public class TCPConnections {

    public HashSet<Integer> establishedConnections = new HashSet<Integer>();
    public HashSet<Integer> listeningConnections = new HashSet<Integer>();

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TCPConnections tcpConnections = new TCPConnections();
        try{        
            do{    
                tcpConnections.getListeningConnections();
                Thread.sleep(5000);
                tcpConnections.getEstablishedConnections();    
            }while(!tcpConnections.establishedConnections.isEmpty());    
        }    
        catch(Exception ex){    
            ex.printStackTrace();    
        }
    }

    public void getEstablishedConnections(){
        String netstat = new String();    
        try {    
                String line;
                establishedConnections = new HashSet<Integer>();
                String[] cmd = {    
                        "/bin/sh",    
                        "-c",    
                        "netstat -atn | grep -w tcp | grep ESTABLISHED"    
                        };

                java.lang.Process p = Runtime.getRuntime().exec(cmd);
                BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

                while ((line = input.readLine()) != null) {    
                    String[] portNo = line.split("\\s+");    
                    if(portNo[3] != null && !portNo[3].equalsIgnoreCase(" ")){    
                        String str = portNo[3].split(":")[1];    
                        if( str != null && str.matches("[0-9]+")){    
                            establishedConnections.add(Integer.parseInt(str));    
                            if(listeningConnections.contains(Integer.parseInt(str))){listeningConnections.remove(Integer.parseInt(str));  
                                System.out.println(" New connection established on port : "+Integer.parseInt(str));    
                            }    
                        }    
                    }    
                        netstat = netstat + " \n" + line;    
                }    
                System.out.println(netstat);    
                input.close();
        } catch (Exception err) {    
                err.printStackTrace();    
        }
    }

    public void getListeningConnections(){    
        String netstat = new String();    
        try {    
                String line;    
                listeningConnections = new HashSet<Integer>();
                String[] cmd = {    
                        "/bin/sh",    
                        "-c",    
                        "netstat -atn | grep -w tcp | grep LISTEN"    
                        };
                java.lang.Process p = Runtime.getRuntime().exec(cmd);    
                BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));    
                while ((line = input.readLine()) != null) {    
                    String[] portNo = line.split("\\s+");    
                    if(portNo[3] != null && !portNo[3].equalsIgnoreCase(" ")){    
                        String str = portNo[3].split(":")[1];    
                        if( str != null && str.matches("[0-9]+")){    
                            listeningConnections.add(Integer.parseInt(str));                        
                        }   
                    }       
                        netstat = netstat + " \n" + line;    
                }    
                System.out.println(netstat);    
                input.close();          
        } catch (Exception err) {    
                err.printStackTrace();    
        }
    }    
}

我面临的问题是,很少有端口始终处于已建立状态,也很少有端口始终处于 Listen 状态,因此 do-while 循环永远运行。请帮我解决这个问题。

【问题讨论】:

  • 这将是最有效的使用操作系统级工具。所以 Java 不是在这里使用的最佳语言。如果真的需要 Java,最好使用 Java 中的某种控制台命令。
  • 我可以在 java exec 中使用 netstat 吗???
  • 为什么? netstat 已经存在。
  • 嗯,你和this guy同班吗?

标签: java linux tcp tcpclient


【解决方案1】:

Java 似乎没有内置任何东西来支持这一点,这并不奇怪,因为类似netstat 的功能依赖于操作系统。

您还有两个选择:

1) 解析netstat的输出:

$ netstat -tn
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 192.168.1.140:48352     74.125.225.134:80       ESTABLISHED

2) 解析/proc/net/tcp(和tcp6udpudp6unix,如果你关心的话):

$ cat /proc/net/tcp
  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
   0: 0100007F:0277 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 17120 1 ffff8800797c4700 100 0 0 10 0
   1: 0100007F:0019 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 14821 1 ffff8800797c4000 100 0 0 10 0
   2: 8C01A8C0:BCE0 86E17D4A:0050 01 00000000:00000000 00:00000000 00000000  1000        0 20164 1 ffff8800797c4e00 24 0 0 10 -1  

这可能看起来更令人生畏,但将是首选方法,因为它不依赖 netstat 的存在(以及您的 PATH 等)

【讨论】:

【解决方案2】:

您可以使用 SNMP 获取 TCPConnTableTCPConnectionTable,无论哪个受支持。

有一个名为 NetSNMP 的 Java SNMP 库,毫无疑问还有其他的。

【讨论】:

    猜你喜欢
    • 2017-05-22
    • 2011-06-18
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    相关资源
    最近更新 更多