import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; /** * Port Scanner */ public class MainClass1 { /** *main entry */ public static void main(String[] args) { String host="localhost"; for(int i=1;i<65536;i++) { try { Socket s=new Socket(host,i);//if there is no server on that port, it will throw a IOException System.out.println("There is a server on port "+i+" of "+host); } catch(UnknownHostException e) { System.out.println(e); break; } catch(IOException e) { System.out.println("there is no server on port "+i); } } } }利用Socket 连接可以得出你要的结果。
http://www.ooppoo.com/html/74/n-99274.html
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Port Scanner
*/
public class MainClass1
{
/**
*main entry
*/
public static void main(String[] args)
{
String host="localhost";
for(int i=1;i<65536;i++)
{
try
{
Socket s=new Socket(host,i);//if there is no server on that port, it will throw a IOException
System.out.println("There is a server on port "+i+" of "+host);
}
catch(UnknownHostException e)
{
System.out.println(e);
break;
}
catch(IOException e)
{
System.out.println("there is no server on port "+i);
}
}
}
}利用Socket 连接可以得出你要的结果。
public static void getHostInterfaceId(){
String line = "";
Process pro = null;
BufferedReader buf = null;
try{
pro = Runtime.getRuntime().exec("netstat -ano");
buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
int i = 0;
while((line = buf.readLine()) != null){
if(line.length() > 0 && i > 3){
String[] strArray = line.split("\\s+");
if(strArray.length>=3){
String s = strArray[2];
String[] sArray = s.split(":");
System.out.println(sArray[1]);
}
}
i++;
}
} catch(Exception e){
e.printStackTrace();
} finally{
try {
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
pro.destroy();
}
}基本思路就是这个具体如何解析字符串的结合你的操作系统来实现,微调一下即可,输出结果是各个被占用端口。