How can I bind serversocket to specific IP?
Asked Answered
A

1

12

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?

Arturoartus answered 20/2, 2013 at 9:54 Comment(0)
M
35

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);
Mercaptopurine answered 20/2, 2013 at 9:58 Comment(6)
You mean pass in my IP and get back the object?Arturoartus
@Jim: Yes, exactly! I have added an example on how to use it.Mercaptopurine
just a note: The default 'backlog' is 50 :D.Indeed
another note: using 0 as backlog will use the default valueBerkeleian
what is 'back log'?Fat
Using "127.0.0.1" will still spawn an IPv6 server as shown by netstat -letW in adb shell.Biodegradable

© 2022 - 2024 — McMap. All rights reserved.