seancfoley / IPAddress

Java library for handling IP addresses and subnets, both IPv4 and IPv6
https://seancfoley.github.io/IPAddress/
Apache License 2.0
466 stars 63 forks source link

strip leading zeros #81

Closed zsobolsky closed 2 years ago

zsobolsky commented 2 years ago

Hi Sean

I've got following ipadress : 010.019.020.30 (from legacy app ...) Is there a way to strip the leading zeros in the segments with this libary, like 10.19.20.30?

Best Regards, Zach

seancfoley commented 2 years ago

Yes. First you must decide if you wish to interpret the leading zero segments as octal. In general, that is how most software handles such addresses. For example, if you point a browser to http://010.010.010.010/ you will see it interpreted as http://8.8.8.8/.

In the example you have provided, it is not possible to interpret that address as octal because the second segment 019 has a nine in it.

So, you have to disallow octal when parsing, using IPAddressStringParameters.

static final IPAddressStringParameters params = 
    new IPAddressStringParameters.Builder().
        getIPv4AddressParametersBuilder().
        allow_inet_aton_octal(false).
        getParentBuilder().toParams();

static String parse(String str) throws AddressStringException {
    IPAddressString addrStr = new IPAddressString(str, params);
    IPAddress addr = addrStr.toAddress();
    return addr.toString();
}

System.out.println(parse("010.019.020.30"));

Output:

10.19.20.30