I'm trying to define a Prototype to store an IP on a Postgres database using the native inet type.
I tried first with toString and getByName, but I got an exception that lead me to think that it's a binary format.
So, I did this:
...
And I got this:
...
Any ideias? Of course I could dump this to a varchar, but this way it would be much cooler.
But you can create a custom class to manage this easily. For the example below, you just have to bound factory method to "valueOf" and conversion method to "toString":
package javax.net;
import java.net.InetAddress;
public class Inet extends Object {
private InetAddress _inetAddress;
private int _bitMask;
public Inet(InetAddress inetAddress, int bitMask) {
super();
if(inetAddress == null) {
throw new IllegalArgumentException("Inet adresse is required.");
} // if
int maxBitMask = (inetAddress.getAddress().length * Byte.SIZE);
if((bitMask < 0) || (bitMask > maxBitMask)) {
throw new IllegalArgumentException(String.format("Bit mask can't be below 0 nor above %d for %s address.", maxBitMask, inetAddress.getHostAddress()));
} // if
_inetAddress = inetAddress;
_bitMask = bitMask;
} // Inet
public Integer bitMask() {
return _bitMask;
} // bitMask
public InetAddress inetAddress() {
return _inetAddress;
} // inetAddress
public static Inet valueOf(String string) {
Inet inet;
if(string != null) {
int bitMask, index;
InetAddress inetAddress;
try {
if((index = string.indexOf('/')) > -1) {
bitMask = Integer.parseInt(string.substring(index + 1));
string = string.substring(0, index);
} else {
bitMask = 0;
} // else
inetAddress = InetAddress.getByName(string);
inet = new Inet(inetAddress, bitMask);
} catch(Exception exception) {
throw new IllegalArgumentException("Can't create valid inet address and mask.", exception);
} // catch
} else {
inet = null;
} // else
return inet;
} // valueOf
public String toString() {
StringBuilder string;
string = new StringBuilder();
string.append(_inetAddress.getHostAddress());
string.append('/');
string.append(_bitMask);
return string.toString();
} // toString
} // Inet