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."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With