Home » Java » How to get InetAddress with wildcard ip 0.0.0.0?

How to get InetAddress with wildcard ip 0.0.0.0?

Posted by: admin December 28, 2021 Leave a comment

Questions:

InetAddress doesn’t provide any static method or constructor to get InetAddress with wildcard IP 0.0.0.0 . The only way is InetAddress.getByName("0.0.0.0")

But PMD gives AvoidUsingHardCodedIP if we pass hard coded IP. Is there any way to get InetAddress with wildcard IP but without hard coding the IP?

Answers:

I know that this is a little bit old. But i was in the same situation:

InetAddress wildCard = new InetSocketAddress(0).getAddress();

does the trick. The main constructor

public InetSocketAddress(InetAddress addr, int port)

will be called with

InetAddress.anyLocalAddress() 

The port is not needed so i picked 0.

###

use InetAddress.getByAddress(new byte[] {0,0,0,0}) will work. but don’t forget to check listen on ipv4 or ipv6.