Static utility methods pertaining to InetAddress instances. Important note: Unlike InetAddress.getByName(), the methods of this class never cause DNS services to be accessed. For this reason, you should prefer these methods as much as possible over their JDK equivalents wh
| 99 | |
| 100 | |
| 101 | @Beta |
| 102 | @GwtIncompatible |
| 103 | public final class InetAddresses { |
| 104 | private static final int IPV4_PART_COUNT = 4; |
| 105 | |
| 106 | private static final int IPV6_PART_COUNT = 8; |
| 107 | |
| 108 | private static final Splitter IPV4_SPLITTER = Splitter.on('.').limit(IPV4_PART_COUNT); |
| 109 | |
| 110 | private static final Inet4Address LOOPBACK4 = (Inet4Address) forString("127.0.0.1"); |
| 111 | |
| 112 | private static final Inet4Address ANY4 = (Inet4Address) forString("0.0.0.0"); |
| 113 | |
| 114 | private InetAddresses() {} |
| 115 | |
| 116 | /** |
| 117 | * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address. |
| 118 | * |
| 119 | * @param bytes byte array representing an IPv4 address (should be of length 4) |
| 120 | * @return {@link Inet4Address} corresponding to the supplied byte array |
| 121 | * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created |
| 122 | */ |
| 123 | |
| 124 | private static Inet4Address getInet4Address(byte[] bytes) { |
| 125 | Preconditions.checkArgument(bytes.length == 4, |
| 126 | "Byte array has invalid length for an IPv4 address: %s != 4.", |
| 127 | bytes.length); |
| 128 | |
| 129 | // Given a 4-byte array, this cast should always succeed. |
| 130 | return (Inet4Address) bytesToInetAddress(bytes); |
| 131 | } |
| 132 | |
| 133 | /** |
| 134 | * Returns the {@link InetAddress} having the given string representation. |
| 135 | * |
| 136 | * <p>This deliberately avoids all nameservice lookups (e.g. no DNS). |
| 137 | * |
| 138 | * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. |
| 139 | * {@code "192.168.0.1"} or {@code "2001:db8::1"} |
| 140 | * @return {@link InetAddress} representing the argument |
| 141 | * @throws IllegalArgumentException if the argument is not a valid IP string literal |
| 142 | */ |
| 143 | |
| 144 | |
| 145 | public static InetAddress forString(String ipString) { |
| 146 | byte[] addr = ipStringToBytes(ipString); |
| 147 | |
| 148 | // The argument was malformed, i.e. not an IP string literal. |
| 149 | if (addr == null) { |
| 150 | throw formatIllegalArgumentException("'%s' is not an IP string literal.", ipString); |
| 151 | } |
| 152 | return bytesToInetAddress(addr); |
| 153 | } |
| 154 | |
| 155 | /** |
| 156 | * Returns {@code true} if the supplied string is a valid IP string literal, {@code false} |
| 157 | * otherwise. |
| 158 | * |