【发布时间】: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同班吗?