4

I have the following simple piece of code which is intended to detect that a given IPv4 address indeed only has numeric values (that is after the dots have been stripped):

import edu.gcc.processing.exceptions.net.IPAddressNumericException;

//Get the IP address
  String address = "239.255.255.255";

//Check to see if this is a number      
  try {
    String IPNumbers = address.replace(".", "");
    Integer.parseInt(IPNumbers);            
  } catch (NumberFormatException e) {
    System.out.print(e.getMessage());
  }

For some reason, the NumberFormatException is fired, and I get this error:

For input string: "239255255255"

Could someone please help me understand this? The parseInt() method works on smaller numbers, such as 127001.

Thank you for your time.

Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195
  • 8
    Well, "what is the range of an integer"? (And why might I have asked that question? :-) –  Dec 07 '11 at 21:29
  • You might want to look into using a regex http://stackoverflow.com/questions/46146/what-are-the-java-regular-expressions-for-matching-ipv4-and-ipv6-strings – Andrew T Finnell Dec 07 '11 at 21:32

6 Answers6

11

try using Long.parseLong(IPNumbers)

PTBG
  • 585
  • 2
  • 20
  • 46
7

Why not use a regular expression, or break it down into its components by using split(".")?

There are other limitations besides needing to consist solely of digits. For example:

666.666.666.666

This will parse just fine, but is an... unlikely IP.

Breaking it up into its parts lets you determine (a) that it has four parts, and (b) that each part actually makes sense in the context of an IP address.

You could also use an InetAddress implementation, or InetAddressValidator from Apache Commons.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
5

For very large integers you may want to use the BigInteger class (or BigDecimal), as the values may exceed the limits of Integer.

Integer Limits:

Minimum : -2147483648
Maximum :  2147483647

Using BigInteger:

string s = "239255255255";
BigInteger yourNumber = new BigInteger(s);
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
3

239255255255 is too big to be held by an Integer. Try using a BigInteger or a BigDecimal.

BenCole
  • 2,092
  • 3
  • 17
  • 26
3

Range of an Integer is -2,147,483,648 to 2,147,483,647, the number you have above mentioned is not included in these range, so use long , the range of long primitive type is in between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.

So for your case its better to use Long.parseLong() function to convert such large number to long type.

Jimshad Abdulla
  • 167
  • 2
  • 8
1

The logical step up from an integer is a long

Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99