Java how to Modify IP Address that was input as a string - java

I have a program that will take a LAN IP provided, I then need to be able to modify just the last octet of the IP's, the first 3 will remain the same based on what was input in the LAN IP Text Field.
For example:
User enter 192.168.1.97 as the LAN IP I need to be able to manipulate the last octet "97", how would I go about doing that so I can have another variable or string that would have say 192.168.1.100 or whatever else i want to set in the last octet.

String ip = "192.168.1.97";
// cut the last octet from ip (if you want to keep the . at the end, add 1 to the second parameter
String firstThreeOctets = ip.substring(0, ip.lastIndexOf(".")); // 192.168.1
String lastOctet = ip.substring(ip.lastIndexOf(".") + 1); // 97
Then, if you want to set the last octet to 100, simply do:
String newIp = firstThreeOctet + ".100"; // 192.168.1.100

You can use these methods
public static byte getLastOctet(String ip) {
String octet = ip.substring (ip.lastIndexOf('.') + 1);
return Byte.parseByte(octet);
}
public static String setLastOctet(String ip, byte octet) {
return ip.substring(0, ip.lastIndexOf ('.') + 1) + octet;
}

Replace the number at the end of the input.
String ipAddress = "192.168.1.97";
String newIpAddress = ipAddress.replaceFirst("\\d+$", "100")

You can do this with the IPAddress Java library as follows. Doing it this way validates the input string and octet value. Disclaimer: I am the project manager.
static IPv4Address change(String str, int lastOctet) {
IPv4Address addr = new IPAddressString(str).getAddress().toIPv4();
IPv4AddressSegment segs[] = addr.getSegments();
segs[segs.length - 1] = new IPv4AddressSegment(lastOctet);
return new IPv4Address(segs);
}
IPv4Address next = change("192.168.1.97", 100);
System.out.println(next);
Output:
192.168.1.100

Related

Identify and get a mobile number from a String

I need to extract a mobile number from a string. I have extracted numbers from string, but failed to get what I need.
Here is the input: a string contains an address and phone number.
String input = "Street1,Punjab Market-Patiala 147001 M:92166-29903"
I need to extract the mobile number, which is 92166-29903.
I use this method to check whether a string contains a mobile number or not:
private Boolean isMobileAvailable(String string)
{
Boolean ismobile = false;
if (string.matches("(?i).*M.*"))
{
ismobile = true;
}
return ismobile;
}
Used in a code as follows:
String mobilenumber="";
private void getMobileNumber(String sample)
{
int index = sample.indexOf("M");
String newString = "";
newString = sample.substring(index, sample.length());
mobileNumber = newString.replaceAll("[^0-9]", "");
edtMobile.setText(mobileNumber.substring(0, 10));
}
Here, instead of mobile number, I am getting 147009211.
How can I identify the mobile number correctly from above string?
int index = sample.lastIndexOf("M");
String newString = sample.substring(index+2, sample.length());
mobileNumber = newString.replaceAll("[^0-9]", "");
edtMobile.setText(mobileNumber.substring(0, 10));
If you want the "-" in your result,just delete mobileNumber = newString.replaceAll("[^0-9]", "");
try this code.
Method 1:
String input = "Street1,Punjab Market-Patiala 147001 M:92166-29903";
int value = input.lastIndexOf(":");
String s = input.substring(value + 1, input.length());
Log.d("reverseString", "" + s);
Method 2:
StringBuffer reverseString=new StringBuffer(input);
StringBuffer s1=reverseString.reverse();
int firstindex=s1.indexOf(":");
String finalstring=s1.substring(0, firstindex);
StringBuffer getexactstring=new StringBuffer(finalstring);
this code will give you exact mobile number that you want.

Assign a variable to a string of text that is between a certain delimiters Ex. “|” using Java

I have a string that I want to break down and assign different part of this string to different variables.
String:
String str ="NAME=Mike|Phone=555.555.555| address 298 Stack overflow drive";
To Extract the Name:
int startName = str.indexOf("=");
int endName = str.indexOf("|");
String name = str.substring(startName +1 , endName ).trim();
But I can't extract the phone number:
int startPhone = arg.indexOf("|Phone");
int endPhone = arg.indexOf("|");
String sip = arg.substring(startPhone + 7, endPhone).trim();
Now how can I extract the phone number that is between delimiter "|".
Also, is there a different way to extract the name using the between delimiter "=" & the first "|"
You can split on both = and | at the same time, and then pick the non-label parts
String delimiters = "[=\\|]";
String[] splitted = str.split(delimiters);
String name = splitted[1];
String phone = splitted[3];
Note that his code assumes that the input is formatted exactly as you posted. You may want to check for whitespace and other irregularities.
String[] details = str.split("|");
String namePart = details[0];
String phonePart = details[1];
String addressPart = details[2];
String name = namePart.substring(namePart.indexOf("=") + 1).trim();
String phone = phonePart.substring(phonePart.indexOf("=") + 1).trim();
String address = addressPart.trim();
I hope this could help.

How to remove specific character from a string?

I have a string that saves user login name and I want to remove specific characters from that string,i want to remove "#gmail.com" and just have the name before the #, then save it as a new string?
How can I do this?
Here's an example, email can be any email address, not just gmail.com
public class Test {
public static void main(String[] args) {
String email = "nobody#gmail.com";
String nameOnly = email.substring(0,email.indexOf('#'));
System.out.println(nameOnly);
}
}
make sure the email format be correct then use "split" method to split the string from '#' character's position and use first portion of results.
var str = "username#amailserver.com";
var res = str.split("#");
var username = res[0];
You can use regex + replaceAll method of string for eliminate it
sample:
String s = "Rod_Algonquin#company.co.nz";
String newS = s.replaceAll("#(.*).(.*)", "");
System.out.println(newS);
will work on different sites extension.
if you want .org, .net , etc then you need to change the regex #(.*).(.*)

What to store an IP as in Java

I am connecting a Java program to a MySQL database, so I need the IP to connect it. Hard coding the IP is obviously a bad idea so I made a config. My only problem is I am not sure what to store the IP as in the variable. I looked around an a lot of places say int, but I don't see how that can be correct because integers don't have decimals. What should I do?
Edit: The answer from Mattias F is more appropriate to your situation. That being said, I'll explain why you've heard that an IP address can be stored in an integer.
An IPv4 address consists of 4 octects, or 4 bytes of data. Incidentally, that's exactly how much information a 32-bit integer can hold. Here are the methods to go both ways:
public static int ipStringToInteger (final String ip)
{
int value = 0;
final String[] parts = ip.split ("\\.");
for (final String part : parts)
value = (value << 8) + Integer.parseInt (part);
return value;
}
public static String ipIntegerToString (int ip)
{
final String[] parts2 = new String[4];
for (int i = 0; i < 4; i++)
{
System.out.println ("Value : " + (ip & 0xff));
parts2[3 - i] = Integer.toString (ip & 0xff);
ip >>= 8;
}
return parts2[0] + '.' + parts2[1] + '.' + parts2[2] + '.' + parts2[3];
}
Edit: Integer.valueOf replace with Integer.parseInt, thanks to Unihedron
As this is in a config file I would just store it all as a string for readability, but you can store it as whatever you want. If this is your IP: "xxx.xxx.xxx.xxx", I would just save it as it is in your config file. Then the rest is dependent on what format your framework for connecting to the database want it on. If it needs a string, you are done, if you need an int[] you just split on "." and do Integer.parseInt on the result from split. Its also possible to have each "xxx" separated with something completely different or even have them on separate lines, but that will both mean more work for you when you parse or lesser readability.
store IP in properties file
Message.properties
#Mysql server Configuration
username = root
password = india
ip = 192.168.1.1
MySQLConnection.java
Properties pro = new Properties();
InputStream in = getClass().getResourceAsStream("Message.properties");
pro.load(in);
String userName = pro.getProperty("username");
String password = pro.getProperty("password");
String IP = pro.getProperty("ip");

How do I get generate an IP address range given start and end IP address?

How can generate a range of IP addresses from a start and end IP address?
Example for a network "192.168.0.0/24":
String start = "192.168.0.2"
String end = "192.168.0.254"
I want to have:
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
...
192.168.0.254
PS: Network, start and end IP can be dynamic above is just an example.
Thanks...
Recognize that each of the 4 components of an IPv4 address is really a hex number between 00 and FF.
If you change your start and end IP addresses into 32 bit unsigned integers, you can just loop from the lowest one to the highest one and convert each value you loop through back into the IP address format.
The range in the example you give is C0A80002 to C0A800FE.
Here's a link to code that converts between a hex number and an IPv4 address
http://technojeeves.com/joomla/index.php/free/58-convert-ip-address-to-number
Here's simple implementation that outputs what you asked for:
public static void main(String args[]) {
String start = "192.168.0.2";
String end = "192.168.0.254";
String[] startParts = start.split("(?<=\\.)(?!.*\\.)");
String[] endParts = end.split("(?<=\\.)(?!.*\\.)");
int first = Integer.parseInt(startParts[1]);
int last = Integer.parseInt(endParts[1]);
for (int i = first; i <= last; i++) {
System.out.println(startParts[0] + i);
}
}
Note that this will only work for ranges involving the last part of the IP address.
Start at 2, count to 254, and put a "192.168.0." in front of it:
for (int i = 2; i <= 254; i++) {
System.out.println("192.168.0." + i);
}
void main(String args[])
{
String start = "192.168.0.2";
String end = "192.168.0.254";
String[] startParts = start.split("(?<=\\.)(?!.*\\.)");
String[] endParts = end.split("(?<=\\.)(?!.*\\.)");
int first = Integer.parseInt(startParts[1]);
int last = Integer.parseInt(endParts[1]);
for (int i = first; i <= last; i++)
{
System.out.println(startParts[0] + i);
}
}
With The IPAddress Java library you can use code that works with both IPv4 and IPv6 transparently. Disclaimer: I am the project manager of the IPAddress library.
Here is sample code:
String start = "192.168.0.2", end = "192.168.0.254";
iterate(start, end);
System.out.println();
start = "::1";
end = "::100";
iterate(start, end);
static void iterate(String lowerStr, String upperStr) throws AddressStringException {
IPAddress lower = new IPAddressString(lowerStr).toAddress();
IPAddress upper = new IPAddressString(upperStr).toAddress();
IPAddressSeqRange range = lower.toSequentialRange(upper);
for(IPAddress addr : range.getIterable()) {
System.out.println(addr);
}
}
Output:
192.168.0.2
192.168.0.3
192.168.0.4
...
192.168.0.254
::1
::2
::3
...
::100

Categories