Why is InetAddress.getByName ("1.2") a valid IP address?

public class InetAddresTest { public static void main(String ... agrs) { try { InetAddress inet = InetAddress.getByName("1.2"); System.out.println("Good ip address"); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

By the way, the IP address of InetAddress is returned as "1.0.0.2". I could not find a reasonable answer from javadoc InetAddress. Can you explain this behavior to someone?

+6
source share
1 answer

From Javadoc (Associated in the "Text View of IP Addresses" in Javadoc for InetAddress ):

When a two-part address is sent, the last part is interpreted as a 24-bit value and placed in the right three bytes of the network address. This makes the two-part address format convenient for specifying class A network addresses as net.host.

Edit to add: In case the 24-bit part confuses you:

2 in 24 bits will look like this: 00000000 00000000 00000010

which is then mapped to the right 3 octets in the IPv4 address as follows: .0.0.2

Another one:. When CoolBeans mentions in the comments on your question, an InetAddressValidator from the Apache community would do the trick. However, if you just want to check IP addresses and not have an external dependency, you can use Regular Expressions to check IP addresses, as well

+7
source

Source: https://habr.com/ru/post/909946/


All Articles