What to store an IP as in Java - 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");

Related

I am not able to make regex for the following String [duplicate]

I have a string like this:
"core/pages/viewemployee.jsff"
From this code, I need to get "viewemployee". How do I get this using Java?
Suppose that you have that string saved in a variable named myString.
String myString = "core/pages/viewemployee.jsff";
String newString = myString.substring(myString.lastIndexOf("/")+1, myString.indexOf("."));
But you need to make the same control before doing substring in this one, because if there aren't those characters you will get a "-1" from lastIndexOf(), or indexOf(), and it will break your substring invocation.
I suggest looking for the Javadoc documentation.
You can solve this with regex (given you only need a group of word characters between the last "/" and "."):
String str="core/pages/viewemployee.jsff";
str=str.replaceFirst(".*/(\\w+).*","$1");
System.out.println(str); //prints viewemployee
You can split the string first with "/" so that you can have each folder and the file name got separated. For this example, you will have "core", "pages" and "viewemployee.jsff". I assume you need the file name without the extension, so just apply same split action with "." seperator to the last token. You will have filename without extension.
String myStr = "core/pages/viewemployee.bak.jsff";
String[] tokens = myStr.split("/");
String[] fileNameTokens = tokens[tokens.length - 1].split("\\.");
String fileNameStr = "";
for(int i = 0; i < fileNameTokens.length - 1; i++) {
fileNameStr += fileNameTokens[i] + ".";
}
fileNameStr = fileNameStr.substring(0, fileNameStr.length() - 1);
System.out.print(fileNameStr) //--> "viewemployee.bak"
These are file paths. Consider using File.getName(), especially if you already have the File object:
File file = new File("core/pages/viewemployee.jsff");
String name = file.getName(); // --> "viewemployee.jsff"
And to remove the extension:
String res = name.split("\\.[^\\.]*$")[0]; // --> "viewemployee"
With this we can handle strings like "../viewemployee.2.jsff".
The regex matches the last dot, zero or more non-dots, and the end of the string. Then String.split() treats these as a delimiter, and ignores them. The array will always have one element, unless the original string is ..
The below will get you viewemployee.jsff:
int idx = fileName.replaceAll("\\", "/").lastIndexOf("/");
String fileNameWithExtn = idx >= 0 ? fileName.substring(idx + 1) : fileName;
To remove the file Extension and get only viewemployee, similarly:
idx = fileNameWithExtn.lastIndexOf(".");
String filename = idx >= 0 ? fileNameWithExtn.substring(0,idx) : fileNameWithExtn;

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

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

How to get multi sub strings from String, Android/Java

I know there are similar questions regarding to this. However, I tried many solutions and it just does not work for me.
I need help to extract multiple substrings from a string:
String content = "Ben Conan General Manager 90010021 benconan#gmail.com";
Note: The content in the String may not be always in this format, it may be all jumbled up.
I want to extract the phone number and email like below:
1. 90010021
2. benconan#gmail.com
In my project, I was trying to get this result and then display it into 2 different EditText.
I have tried using pattern and matcher class but it did not work.
I can provide my codes here if requested, please help me ~
--------------------EDIT---------------------
Below is my current method which only take out the email address:
private static final String EMAIL_PATTERN =
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+";
public String EmailValidator(String email) {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
if (matcher.find()) {
return email.substring(matcher.start(), matcher.end());
} else {
// TODO handle condition when input doesn't have an email address
}
return email;
}
You can separate your string into arraylist like this
String str = "Ben Conan, General Manager, 90010021, benconan#gmail.com";
List<String> List = Arrays.asList(str.split(" "));
maybe you should do this instead of yours :
String[] Stringnames = new String[5]
Stringnames [0] = "your phonenumber"
Stringnames[1] = "your email"
System.out.println(stringnames)
Or :
String[] Stringnames = new String[2]
String[] Stringnames = {"yournumber","your phonenumber"};
System.out.println(stringnames [1]);
String.split(...) is a java method for that.
EXAMPLE:
String content = "Ben Conan, General Manager, 90010021, benconan#gmail.com";
String[] selection = content.split(",");
System.out.println(selection[0]);
System.out.println(selection[3]);
BUT if you want to do a Regex then take a look at this:
https://stackoverflow.com/a/16053961/982161
Try this regex for phone number
[\d+]{8} ---> 8 represents number of digits in phone number
You can use
[\d+]{8,} ---> if you want the number of more than 8 digits
Use appropriate JAVA functions for matching. You can try the results here
http://regexr.com/
For email, it depends whether the format is simple or complicated. There is a good explanation here
http://www.regular-expressions.info/index.html

searching for right ip address in an array of strings - java android

I'm new to android java programming. I'm trying to rewrite an app.
i had an editText contaning ip prefixes delimited by ",". e.g. "10.15,10.31,10.42"
private void MDConnect() {
String str = getIpAddress();
String [] arrayOfString = editText.getText().toString().split(",");
j = 0
while ( j < arrayOfString.length) {
if (str.substring(0,arrayOfString[j].length()).equals(arrayOfString[j])){
addMessage("Success! Your IP address is " + str);
}else{
j++;}
}
addMessage("Retrying")
// this is where the process will start over. disconnect and then connect to get a fresh new ip address
}
my goal is to connect->getIpAdd->check if it matches the ones on the list->if yes, add success message; if no, disconnect and connect again.
Hope someone could help me. Please. Thanks in advance.
EDIT:the code is just checking the first string in the array. it's not looping or moving to the next string. How could i loop an if-statement and do the process i have said in my post?
Your code is very sloppy and is missing semi-colons and closing brackets. And your loop can be simplified a lot, although your method CAN work, you are making it much harder than it should be. try this code:
String str = getIpAddress();
String [] arrayOfString = editText.getText().toString().split(",");
for (int i = 0; i < arrayOfString.length; i++) {
if (str.substring(0,arrayOfString[i].length()).equals(arrayOfString[i])) {
addMessage("Success! Your IP address is " + str);
break;
} else {
//not found
addMessage("Retrying")
}
}
Move the addMessage("Retrying") and disconnect logic outside of the loop, so that it is not executed until it has tried and failed to match on all of the IPs in the array:
private void MDConnect() {
String ip = getIpAddress();
String[] prefixes = editText.getText().toString().split(",");
for (String prefix : prefixes) {
if (ip.startsWith(prefix)) {
addMessage("Success! Your IP address is " + ip);
return;
}
}
addMessage("Retrying");
...
}

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