在命令列輸入一串主機名稱,並嘗試對各個主機開啟一個Socket
印出遠端主機、遠端通訊埠、本地位址及本地通訊埠
import java.net.*;
import java.io.*;
public class SocketInfo{
public static void main(String[] args){
for(int i = 0; i < args.length; i++){
try{
Socket s = new Socket(args[i], 80);
System.out.println("Connected to " + s.getInetAddress()
+ "on port " + s.getPort() + " from port "
+ s.getLocalPort() + " of "
+ s.getLocalAddress());
}
catch(UnknownHostException ex){
System.err.println("I can't find " + args[i]);
}
catch(SocketException ex){
System.err.println("Could not connect to " + args[i]);
}
catch(IOException ex){
System.err.println(ex);
}
}//for end
}//main end
}//SocketInfo end
參考資料:Java網路程式設計 第三版(歐萊禮出版) 第九章範例