public static Inet4Address getCoercedIPv4Address ( InetAddress ip ) { if ( ip instanceof Inet4Address ) { return ( Inet4Address ) ip ; } // Special cases: byte [ ] bytes = ip . getAddress ( ) ; boolean leadingBytesOfZero = true ; for ( int i = 0 ; i < 15 ; ++ i ) { if ( bytes [ i ] != 0 ) { leadingBytesOfZero = false ; break ; } } if ( leadingBytesOfZero && ( bytes [ 15 ] == 1 ) ) { return LOOPBACK4 ; // ::1 } else if ( leadingBytesOfZero && ( bytes [ 15 ] == 0 ) ) { return ANY4 ; // ::0 } Inet6Address ip6 = ( Inet6Address ) ip ; long addressAsLong = 0 ; if ( hasEmbeddedIPv4ClientAddress ( ip6 ) ) { addressAsLong = getEmbeddedIPv4ClientAddress ( ip6 ) . hashCode ( ) ; } else { // Just extract the high 64 bits (assuming the rest is user-modifiable). addressAsLong = ByteBuffer . wrap ( ip6 . getAddress ( ) , 0 , 8 ) . getLong ( ) ; } // Many strategies for hashing are possible. This might suffice for now. int coercedHash = Hashing . murmur3_32 ( ) . hashLong ( addressAsLong ) . asInt ( ) ; // Squash into 224/4 Multicast and 240/4 Reserved space (i.e. 224/3). coercedHash |= 0xe0000000 ; // Fixup to avoid some "illegal" values. Currently the only potential // illegal value is 255.255.255.255. if ( coercedHash == 0xffffffff ) { coercedHash = 0xfffffffe ; } return getInet4Address ( Ints . toByteArray ( coercedHash ) ) ; }
Coerces an IPv6 address into an IPv4 address .