0
votes

Is there any way that InetAddress.getByName( 234324.32423.234234.324234 ) will return a non-null address value? Seems like it does.

Since this happens in a unit test, all I have to do is force InetAddress to throw an exception. Is there any reason why the following mock using PowerMock won't work? I do have the annotations @RunWith(PowerMockRunner.class) and @PrepareForTest({InetAddress.class}) before my class signature

String testIp = "127.0.0.1";
PowerMockito.mockStatic( InetAddress.class );
PowerMockito.when( InetAddress.getByName( testIp ) ).thenThrow( UnknownHostException.class );
MyClass someClassThatCallsInetAddressGetByName = new MyClass( 32 );
someClassThatCallsInetAddressGetByName.setHostAddress( testIp );
someClassThatCallsInetAddressGetByName.getHostAddress();
2
I don't know if this is you case, but some platforms truncate the decimal part of any format valid IP (Number (dot) Number (dot) Number (dot) Number) and return the result IP of this operation.Tuxman
what exact "valid address" does it return?Alnitak

2 Answers

4
votes

Is 234324.32423.234234.324234 a valid InetAddress?

No.

It is not a valid IPv4 address because the numbers in a 4-part IPv4 address are decimal numbers in the range 0 to 255.

It won't parse as an IPv6 address because the components of an IPv6 address are separated by colons rather than dots. (The alternative IPv6 formats have colons AND dots ... but at least one colon is always present.)

References:


In my local environment, it returns null. But when migrated to cloud, it seems to return a valid address.

It should always return null. That is not a valid IP address string ... according to the javadocs. (What do you mean by "migrated to cloud"? Are you translating the code to a different language?)

Is this possible? Is InetAddress platform dependent?

It shouldn't be, and No1.

And for the record the IPv4 address parsing in OpenJDK does check the ranges of the component numbers.


1 - At least not for any recent version of Java that is compliant to the spec. A non-compliant implementation might, but then it would not be Java(tm).

0
votes

Not 100% sure, but your address get probably parsed as an IPv6. In your local env, you have no such resolution, but in the cloud someone responds to it?

According to the doc here, getByName may resolve to IPv6 too.