Welcome, Guest
Username: Password: Remember me

TOPIC: Parsing and printing Ipv4 and Ipv6 as decimals

Parsing and printing Ipv4 and Ipv6 as decimals 4 years 4 months ago #115

  • John
  • John's Avatar
  • Offline
  • Karma: 2
It may come in handy to convert ip addresses to decimal numbers. As decimals the addresses can then be compared as regular numbers. One way to do this with Java is using the BigInteger class.
public class IpToDecimal {

    public static void main(String[] args) throws UnknownHostException {

        printAddress(InetAddress.getByName("127.0.0.1"));

        printAddress(InetAddress.getByName("::1"));

        printAddress(InetAddress.getByName("fe80::c68e:8fff:fef8:873f"));

        printAddress(InetAddress.getByName("2001:420:c0dc:8000:c68e:8fff:fef8:873f"));

        printAddress(InetAddress.getByName("2001:470:0:284::100:0"));
    }

    private static void printAddress(InetAddress ipAddress) {

        out.println(ipAddress.toString().split("/")[1]);
        out.println(new BigInteger(1, ipAddress.getAddress()));

        if (ipAddress instanceof Inet4Address) out.println("Inet4Address");
        else out.println("Inet6Address");

        out.println("Is Any: " + ipAddress.isAnyLocalAddress());
        out.println("Is Link Local: " + ipAddress.isLinkLocalAddress());
        out.println("Is Site Local: " + ipAddress.isSiteLocalAddress());
        out.println("Is Loopback: " + ipAddress.isLoopbackAddress());
        out.println("Is Multicast: " + ipAddress.isMulticastAddress());

        out.println();
    }
}
John Monash
Last Edit: 4 years 4 months ago by John.
The administrator has disabled public write access.
Powered by Kunena Forum