How can I bind serversocket to specific IP?

只愿长相守 提交于 2019-12-23 07:47:27

问题


If I have a String representing an IP address (IPv4 or IPv6) how can I create a ServerSocket and bind to this IP without caring if the IP passed in, is IPv4 or IPv6?
I see that there is a constructor:ServerSocket(int port, int backlog, InetAddress bindAddr) but InetAddress does not seem to offer any constructors and its subclasses have names specific to IPv4 and IPv6.
So how can I bind the socket to the IP?


回答1:


You can use the factory method INetAddress.getByName. It'll figure out which subclass to use. For example:

InetAddress addr = InetAddress.getByName("127.0.0.1");
// or
InetAddress addr = InetAddress.getByName("::1");

// and now you can pass it to your socket-constructor
ServerSocket sock = new ServerSocket(1234, 50, addr);


来源:https://stackoverflow.com/questions/14976867/how-can-i-bind-serversocket-to-specific-ip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!