4

What is the best type for storing IP-addresses in a database using Hibernate?

I though Byte[] or String, but is there a better way, or what do you use?

 @Column(name = "range_from",  nullable = false)
 public Byte[] getRangeFrom() {
  return rangeFrom;
 }
 public void setRangeFrom(Byte[] rangeFrom) {
  this.rangeFrom = rangeFrom;
 }
Michel
  • 9,220
  • 13
  • 44
  • 59

2 Answers2

7

I store it in a long, very fast for lookup. You can use the following functions for conversion.

public static string GetStandardIP(long numericIP)
{
    string w = Convert.ToString(Convert.ToInt64(numericIP / 16777216) % 256);
    string x = Convert.ToString(Convert.ToInt64(numericIP / 65536) % 256);
    string y = Convert.ToString(Convert.ToInt64(numericIP / 256) % 256);
    string z = Convert.ToString(Convert.ToInt64(numericIP) % 256);

    return w + "." + x + "." + y + "." + z;
}

And this one

public static long GetNumericIP(string standardIP)
{
    if (standardIP != null && standardIP != string.Empty)
    {
        string[] ipParts = standardIP.Split('.');
        long numericIP = 16777216 * Convert.ToInt64(ipParts[0]) + 65536 * Convert.ToInt64(ipParts[1]) + 256 * Convert.ToInt32(ipParts[2]) + Convert.ToInt32(ipParts[3]);

        return numericIP;
    }
    return 0;
}

You may want to improve them by doing checks on the parameters.

Richard
  • 29,854
  • 11
  • 77
  • 120
  • 1
    Yes you want it translated into another language ? –  Jul 29 '10 at 19:33
  • No thank you, I translated it myself in Java. Thx for you answer! – Michel Jul 30 '10 at 08:44
  • 3
    Instead of "(numericIP / 16777216) % 256" you could use bit shift operation: "numericIp << 24". This will communicate the intention more clearly and the person reading the code won't be tempted to check, if you got 2^24 correctly – sesm Jan 29 '14 at 13:29
2

It doesn't matter too much if you use Byte[] or String. Both will do the same job, it really just depends on your application and requirements.

I personally have always stored them as Strings.

I'm not aware of a better way to store them via Hibernate.

See https://forum.hibernate.org/viewtopic.php?f=1&t=996818&start=0

edit: Or you can use a long as in Pierre 303's example. In the end it really depends on your application and which type is the easiest to deal with for you.

Ross
  • 511
  • 3
  • 12