File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes IP Address Format Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "IP Address Format" Watch "IP Address Format" New topic

IP Address Format

Nee Kat
Ranch Hand

Joined: Jan 27, 2004
Posts: 37
I have to check for the valid IP Address that is being entered by the user before the IP Address is used for querying the database.

Here are the rules:

if someone enters leading zeroes, for example 192.051 or 192.051.088 the leading zero would be stripped ip address used will be 192.51 or 192.51.88


IP Address should have periods at right places


are all valid entries where as

1922788128 are invalid.

I have found this code on net but I am unable to figure it out. I have never heard of "var" before in JAVA.

function isValidIPAddress(ipaddr) {
var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
if (re.test(ipaddr)) {
var parts = ipaddr.split(".");
if (parseInt(parseFloat(parts[0])) == 0) { return false; }
for (var i=0; i<parts.length; i++) {
if (parseInt(parseFloat(parts[i])) > 255) { return false; }
return true;
} else {
return false;

Please help!
[ December 02, 2004: Message edited by: Nee Kat ]
Barry Higgins
Ranch Hand

Joined: Jun 05, 2003
Posts: 89
I would suggest using Patterns you can use groups with this to check extract the digits you require ([1-9]{0,3}) and put a 0* before them to exclude the leading zeros.
If you've any problems post back.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
I think Barry is suggesting making use of a regular expression pattern and matcher. The pattern he suggested would match invalid IP addresses, as well as valid IP addresses.

If regular expressions are completely new to you, you might like to take a look at the two introductory articles on the subject I wrote for The JavaRanch Journal.

If you're looking for a pattern to use, I recommend trying a quick search at
[ December 02, 2004: Message edited by: Dirk Schreckmann ]

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Scott Dunbar
Ranch Hand

Joined: Sep 23, 2004
Posts: 245
Another way would be to do a getByName():

A quick test shows that printing out with getHostAddress() strips the zeros. If the input is bogus then it throws an UnknownHostException. One advantage is that this handles IPV6 address formats too.
[ December 02, 2004: Message edited by: Scott Dunbar ]

<a href="" target="_blank" rel="nofollow">Java forums using Java software</a> - Come and help get them started.
I agree. Here's the link:
subject: IP Address Format
It's not a secret anymore!