Search code examples
javainetaddress

Using InetSocketAddress correctly


I am attempting to use the InetSocketAddress that is part of Java.net. Although when I try to actually give it data for its perimeters it does not work. The documentation does not actually specify how to define the IP address and port. It states it goes as follows: InetSocketAddress(InetAddress addr, int port) , addr being the IP address. I have tried the following ways:

InetSocketAddress("0.0.0.0", 0000)

InetSocketAddress(0.0.0.0, 0000)

InetSocketAddress(0.0.0.0:0000)

Obviously none of these work (using arbitrary values), all but the last, the port works cause it's just an int but I can't figure out how to format the IP address correctly. The docs I have read over in search of a solution are as follows:

InetAddress

Inet4Address

InetSocketAddress

None of these actaully have an example of how to format the IP address (unless I'm blind of course).


Solution

  • InetSocketAddress wants an InetAddress object for the first parameter. So you need to send it one with something like:

    InetSocketAddress(InetAddress.getByName("0.0.0.0", 0))

    I know, getByName() doesn't sound like it should be used with an IP address, but it works with both an address or host name.