简体   繁体   English

IP地址的哈希函数

[英]Hash Function For IP Address

I need to generate a unique ID(a string) from a ip address and vice-versa. 我需要从IP地址生成唯一的ID(字符串),反之亦然。 The unique Id must be of 8-9 character. 唯一ID必须为8-9个字符。 Is there any has function which could do that in java? 有没有可以在Java中执行的功能?

Since an IPv4 Address consists of 4 Bytes, you could simply use the hex representation, which would result in 8 characters 由于IPv4地址由4个字节组成,因此您可以简单地使用十六进制表示形式,这将导致8个字符

This could be an implementation: 这可以是一个实现:

public static String ipToId(String ip) {
    return Arrays.stream(ip.split("\\."))
        .map(Integer::parseInt)
        .map(number -> String.format("%02X", number))
        .collect(Collectors.joining());
}

The reverse could be done via: 可以通过以下方法完成相反的操作:

public static String idToIp( String id )
{
    return Stream.of( id )
            .map( Base64.getDecoder()::decode )
            .flatMapToInt( bytes -> IntStream.range( 0, bytes.length )
                    .map( index -> bytes[index] & 0xFF ) )
            .mapToObj( String::valueOf )
            .collect( Collectors.joining( "." ) );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM