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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With