Java examples for Network:IP Address
Convert an IPv4 INET address to an integer.
/*/*from w ww. ja va2 s.c o m*/ * Copyright (c) 2004 by Cosylab * * The full license specifying the redistribution, modification, usage and other * rights and obligations is included with the distribution of this project in * the file "LICENSE-CAJ". If the license is not included visit Cosylab web site, * <http://www.cosylab.com>. * * THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, NOT EVEN THE * IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE, ASSUMES * _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, * OR REDISTRIBUTION OF THIS SOFTWARE. */ //package com.java2s; import java.net.Inet6Address; import java.net.InetAddress; public class Main { /** * Convert an IPv4 INET address to an integer. * @param addr IPv4 INET address. * @return integer representation of a given address. * @throws IllegalArgumentException if the address is really an IPv6 address */ public static int ipv4AddressToInt(InetAddress addr) { if (addr instanceof Inet6Address) throw new IllegalArgumentException( "IPv6 address used in IPv4 context"); byte[] a = addr.getAddress(); int res = ((a[0] & 0xFF) << 24) | ((a[1] & 0xFF) << 16) | ((a[2] & 0xFF) << 8) | (a[3] & 0xFF); return res; } }