测试代码
//将172.16.12.171 替换为 xingyun25 打印结果一致 Socket sock = new Socket("172.16.12.171",12331); InetAddress netAddress = sock.getInetAddress(); System.out.println(netAddress.getHostName()); System.out.println(netAddress.getHostAddress()); sock.close();
打印结果
xingyun25 172.16.12.171
查看 Socket
方法
public Socket(String host, int port) throws UnknownHostException, IOException { //host != null 因此第一个参数为new InetSocketAddress(host, port) this(host != null ? new InetSocketAddress(host, port) : new InetSocketAddress(InetAddress.getByName(null), //第二个参数 (SocketAddress) null //第三个参数 true (SocketAddress) null, true); }
查看 this 构造方法
private Socket(SocketAddress address, SocketAddress localAddr, boolean stream) throws IOException { setImpl(); // backward compatibility if (address == null) throw new NullPointerException(); try { createImpl(stream); if (localAddr != null) //localhost/127.0.0.1 bind(localAddr); //建立连接 connect(address); } catch (IOException | IllegalArgumentException | SecurityException e) { try { close(); } catch (IOException ce) { e.addSuppressed(ce); } throw e; } }
对于 setImpl 方法
void setImpl() { if (factory != null) { impl = factory.createSocketImpl(); checkOldImpl(); } else { // No need to do a checkOldImpl() here, we know it's an up to date // SocketImpl! impl = new SocksSocketImpl(); } //Impl SET Socket if (impl != null) impl.setSocket(this);}
对于 createImpl 方法
// SocketImpl impl :The implementation of this Socket. void createImpl(boolean stream) throws SocketException { if (impl == null) setImpl(); try { impl.create(stream); created =true; } catch (IOException e) { throw new SocketException(e.getMessage()); } }
查看InetSocketAddress方法通过IP和域名创建有何不同
public InetSocketAddress(String hostname, int port) { checkHost(hostname); InetAddress addr = null; String host = null; try { addr = InetAddress.getByName(hostname); } catch(UnknownHostException e){ host = hostname; } //实际构造了 InetSocketAddressHolder holder = new InetSocketAddressHolder(host, addr, checkPort(port)); }
connect 过程中实际使用的是 InetAddress private InetSocketAddressHolder(String hostname, InetAddress addr, int port) { this.hostname = hostname; this.addr = addr; this.port = port; }
————————————————