views:

48

answers:

2

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;
 }
+1  A: 

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.

Rosco
+1  A: 

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.

Pierre 303
you use this in c#?
michel
Yes you want it translated into another language ?
Pierre 303
No thank you, I translated it myself in Java. Thx for you answer!
michel