简体   繁体   中英

How come InetAddress.getByName(“1.2”) is 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();
        }
    }
}   

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM