3

I am experimenting with websockets and I want to make it connect to local network automatically from another computer on the LAN and since there are 255 possible computers on the same network I want it to try all and then connect to whichever it can connect to first. However, first part of an IP address, 192.168.1.*, is different based on router settings.

I can get the whole current IP address of the machine, then I want to extract the front part.

For example

25.0.0.5 will become 25.0.0.
192.168.0.156 will become 192.168.0.
192.168.1.5 will become 192.168.1.

and so on

 String Ip  = "123.345.67.1";
 //what do I do here to get IP == "123.345.67."

4 Answers 4

3

You can use a regex for this:

String Ip  = "123.345.67.1";
String IpWithNoFinalPart  = Ip.replaceAll("(.*\\.)\\d+$", "$1");
System.out.println(IpWithNoFinalPart);

A quick regex explanation: (.*\\.) is a capturing group that holds all characters up to the last . (due to greedy matching with * quantifier), \\d+ matches 1 or several digits, and $ is the end of string.

Here is a sample program on TutorialsPoint.

Sign up to request clarification or add additional context in comments.

Comments

1
String Ip  = "123.345.67.1";
String newIp = Ip.replaceAll("\\.\\d+$", "");
System.out.println(newIp);

Output:

123.345.67

Explanation:

\.\d+$

Match the character “.” literally «\.»
Match a single character that is a “digit” «\d+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Assert position at the end of the string, or before the line break at the end of the string, if any «$»

Demo:

http://ideone.com/OZs6FY

Comments

0

Instead of a regex you could make use of String.lastIndexOf('.') to find the last dot and String.substring(...) to extract the first part as follows:

String ip = "192.168.1.5";
System.out.println(ip.substring(0, ip.lastIndexOf('.') + 1));
// prints 192.168.1.

2 Comments

This would fail if the number after the last dot is more than 9.
@OmarAli that's not true, it will work regardless of how many characters are behind the last dot
-1

Just split the string on the dot "." If the string is a valid IP Address string, then you should then have a String[] array with 4 parts, you can then join only the first 3 with a dot "." and have the "front part"

i.e.



    String IPAddress = "127.0.0.1";
    String[] parts = IPAddress.split(".");

    StringBuffer frontPart = new StringBuffer();
    frontPart.append(parts[0]).append(".")
             .append(parts[1]).append(".")
             .append(parts[2]).append(".");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.