Java之InetSocketAddress和SocketAddress的區別

lvxiangan發表於2018-11-15

兩者區別:SocketAddress是一個抽象類,而InetSocketAddress 是SocketAddress的子類。

示例:

InetAddress address = InetAddress.getLocalHost();
String hostName = address.getHostName();
String hostAddr = address.getHostAddress();
System.out.println("主機名:" + hostNmae + ", ip地址:"  + hostAddr;

InetAddress add = InetAddress.getByName("BOPZKQZ9SSY5ECY");
System.out.println(add.getHostAddress());

final Socket socket = new Socket();
SocketAddress address = new InetSocketAddress("www.fortify.net", 443);
try {
    socket.connect(address);
} catch (IOException e) {}
// 連線遠端主機
Thread reader = new Thread() {
    @Override
    public void run() {
        try {
            byte[] buffer = new byte[512];
            InputStream stream = socket.getInputStream();
            socket.getInputStream().read(buffer);
        } catch (Exception ex) {
 
        }
    }
};
reader.start();


 

相關文章