6
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 ?

user429061
  • 61
  • 2
  • 1
    Brian is spot on with his answer. If your goal is to validate IP address then I recommend you use Apache-Commons [InetAddressValidator](http://commons.apache.org/validator/apidocs/org/apache/commons/validator/routines/InetAddressValidator.html) – CoolBeans Mar 04 '12 at 17:21
  • 1
    @CoolBeans - added that to the answer, with an alternative as well - thanks. – Brian Roach Mar 04 '12 at 17:49
  • The Apache Commons InetAddressValidator can help only if you're validating IPv4 only, as the current release (1.4) doesn't seem to support IPv6. – Douglas Jan 03 '13 at 21:45

1 Answers1

8

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

Community
  • 1
  • 1
Brian Roach
  • 76,169
  • 12
  • 136
  • 161