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?
Asked
Active
Viewed 3.4k times
12

Jim
- 18,826
- 34
- 135
- 254
1 Answers
34
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);
-
You mean pass in my IP and get back the object? – Jim Feb 20 '13 at 09:58
-
@Jim: Yes, exactly! I have added an example on how to use it. – vstm Feb 20 '13 at 10:00
-
4just a note: The default 'backlog' is 50 :D. – Aug 09 '14 at 10:46
-
2another note: using `0` as backlog will use the default value – kapex Oct 24 '16 at 13:43
-
1what is 'back log'? – Eboubaker Dec 01 '19 at 17:43