Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

IP Address Format

 
Nee Kat
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

and

IP Address should have periods at right places


like 192.27.88.128
192.27.88
192.27
192

are all valid entries where as

192.2788128
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
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Barry
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 http://regexlib.com.
[ December 02, 2004: Message edited by: Dirk Schreckmann ]
 
Scott Dunbar
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic