Add ipv4AddressToInt(Inet4Address) in NetUtils (#10500)
Motivation: We're converting `Inet4Address` to `Integer` quite frequently so it's a good idea to keep that code in `NetUtils`. Modification: Added ipv4AddressToInt(Inet4Address) in NetUtils Result: Easy conversion of `Inet4Address` to `Integer`.
This commit is contained in:
parent
6c1840749d
commit
fde6bc8885
@ -416,6 +416,18 @@ public final class NetUtil {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert {@link Inet4Address} into {@code int}
|
||||
*/
|
||||
public static int ipv4AddressToInt(Inet4Address ipAddress) {
|
||||
byte[] octets = ipAddress.getAddress();
|
||||
|
||||
return (octets[0] & 0xff) << 24 |
|
||||
(octets[1] & 0xff) << 16 |
|
||||
(octets[2] & 0xff) << 8 |
|
||||
octets[3] & 0xff;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a 32-bit integer into an IPv4 address.
|
||||
*/
|
||||
|
@ -18,6 +18,7 @@ package io.netty.util;
|
||||
import io.netty.util.internal.StringUtil;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.Inet4Address;
|
||||
import java.net.Inet6Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
@ -724,6 +725,12 @@ public class NetUtilTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIPv4ToInt() throws UnknownHostException {
|
||||
assertEquals(2130706433, ipv4AddressToInt((Inet4Address) InetAddress.getByName("127.0.0.1")));
|
||||
assertEquals(-1062731519, ipv4AddressToInt((Inet4Address) InetAddress.getByName("192.168.1.1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIpv4MappedIp6GetByName() {
|
||||
for (Entry<String, String> testEntry : ipv4MappedToIPv6AddressStrings.entrySet()) {
|
||||
|
Loading…
Reference in New Issue
Block a user