直接上代码:
private static String command=" netstat -ano ";
public static void main(String[] args) {
Process p = null;try {
p = Runtime.getRuntime().exec(command);
InputStream fis=p.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(fis, Charset.forName("GBK")));
String line=null;
while((line=br.readLine())!=null)
{
if (line.contains("LISTENING")){
System.out.println( line );
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
完善:
private static void windows(String port) {
List<String> pids = new ArrayList<>();
String cmd = " cmd /c netstat -ano|findstr " + port;
Process p = null;
try {
p = Runtime.getRuntime().exec(cmd);
// Runtime.exec()创建的子进程公用父进程的流,不同平台上,父进程的stream buffer可能被打满导致子进程阻塞,从而永远无法返回。
//针对这种情况,我们只需要将子进程的stream重定向出来即可。
InputStream fis = p.getInputStream();
//用缓冲器读行
BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("GBK")));
String line = null;
//直到读完为止
while ((line = br.readLine()) != null) {
pid = line.split(" ")[line.split(" ").length - 1];
if (pids.contains(pid)) {
continue;
} else {
pids.add(pid);
}
System.out.println(pid);
taskList(pid);
}
p.waitFor();
br.close();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void taskList(String pid) {
String cmd = " cmd /c tasklist|findstr " + pid;
Process p = null;
try {
p = Runtime.getRuntime().exec(cmd);
// Runtime.exec()创建的子进程公用父进程的流,不同平台上,父进程的stream buffer可能被打满导致子进程阻塞,从而永远无法返回。
//针对这种情况,我们只需要将子进程的stream重定向出来即可。
InputStream fis = p.getInputStream();
//用缓冲器读行
BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("GBK")));
String line = null;
//直到读完为止
while ((line = br.readLine()) != null) {
System.out.println(line.split(" ")[0]);
}
p.waitFor();
br.close();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}