Darth Blue Ray
Darth Blue Ray

Reputation: 9745

Getting a part of IP address String

If I have a IP address String like : 10.120.230.78 I would like to get 10.120. out of it

But the parts of the address can change from 1 tot 3 numbers as we all know ...

1.1.1.1 to 255.255.255.255 so ....

I believe you can use a pattern, but I don't have an idea how to.

Upvotes: 2

Views: 5731

Answers (4)

Cengiz
Cengiz

Reputation: 4867

  1. The best way is String.split() as already mentioned by amit. E.g.

    String[] ipAddressParts = ipAddress.split();
    
  2. Also you can use

    StringTokenizer stringTokenizer = new StringTokenizer( ipAddress, "." );
    while ( stringTokenizer.hasMoreTokens() )  {
      System.out.println( stringTokenizer.nextToken() );
    }
    
  3. java.util.Scanner

Upvotes: 1

Fredrik
Fredrik

Reputation: 1302

Take a look at String.split() it's equivalent to php's explode()

Upvotes: 0

user228534
user228534

Reputation:

ip.substring(0, ip.indexOf('.',ip.indexOf('.') + 1) + 1)

where ip is the string holding the IP address.

Upvotes: 2

amit
amit

Reputation: 178411

assume you store your ip as a string called ip, you can use String.split() to get an array of the parts:

String[] tokens = ip.split("\\.");

Upvotes: 12

Related Questions