Reputation: 311
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?
Upvotes: 2
Views: 1665
Reputation: 709
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
Upvotes: 5
Reputation: 7249
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");
Upvotes: 0
Reputation: 632
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.
Upvotes: 2