简体   繁体   中英

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM