Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come InetAddress.getByName("1.2") is valid ip address?

Tags:

java

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();
        }
    }
}   

BTW the InetAddress produced ip address comes back as "1.0.0.2" . I could not find a reasonable answer from the javadoc of InetAddress. Can you someone explain this behaviour ?

like image 415
user429061 Avatar asked Mar 04 '12 17:03

user429061


1 Answers

From the Javadoc (Linked in "Textual representation of IP addresses" in the Javadoc for InetAddress ):

When a two part address is supplied, the last part is interpreted as a 24-bit quantity and placed in the right most 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 24bit part is confusing to you:

2 in 24bit would look like: 00000000 00000000 00000010

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

One More: As CoolBeans mentions in the comments to your question, the InetAddressValidator from Apache commons would do the trick. That being said, if you just want to validate IP addresses and not have an external dependency, you can use Regular Expressions to check IP addresses as well

like image 74
Brian Roach Avatar answered Oct 24 '22 19:10

Brian Roach