How can I bind serverocket to a specific IP?

If I have a String representing an IP address (IPv4 or IPv6), how can I create a ServerSocket and bind to that IP address without worrying about whether the IP address passed, 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 a socket to IP?

+6
source share
1 answer

You can use the factory method INetAddress.getByName . He will figure out which subclass to use. For instance:

 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); 
+20
source

All Articles