Java Code Examples for io.netty.util.NetUtil#isValidIpV4Address()

The following examples show how to use io.netty.util.NetUtil#isValidIpV4Address() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Endpoint.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new host endpoint with the specified IP address.
 *
 * @return the new endpoint with the specified IP address.
 *         {@code this} if this endpoint has the same IP address.
 *
 * @throws IllegalStateException if this endpoint is not a host but a group
 */
public Endpoint withIpAddr(@Nullable String ipAddr) {
    if (ipAddr == null) {
        return withoutIpAddr();
    }

    if (NetUtil.isValidIpV4Address(ipAddr)) {
        return withIpAddr(ipAddr, StandardProtocolFamily.INET);
    }

    if (NetUtil.isValidIpV6Address(ipAddr)) {
        if (ipAddr.charAt(0) == '[') {
            ipAddr = ipAddr.substring(1, ipAddr.length() - 1);
        }
        return withIpAddr(ipAddr, StandardProtocolFamily.INET6);
    }

    throw new IllegalArgumentException("ipAddr: " + ipAddr + " (expected: an IP address)");
}
 
Example 2
Source File: Socks5ProxyHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private void sendConnectCommand(ChannelHandlerContext ctx) throws Exception {
    InetSocketAddress raddr = destinationAddress();
    Socks5AddressType addrType;
    String rhost;
    if (raddr.isUnresolved()) {
        addrType = Socks5AddressType.DOMAIN;
        rhost = raddr.getHostString();
    } else {
        rhost = raddr.getAddress().getHostAddress();
        if (NetUtil.isValidIpV4Address(rhost)) {
            addrType = Socks5AddressType.IPv4;
        } else if (NetUtil.isValidIpV6Address(rhost)) {
            addrType = Socks5AddressType.IPv6;
        } else {
            throw new ProxyConnectException(
                    exceptionMessage("unknown address type: " + StringUtil.simpleClassName(rhost)));
        }
    }

    ctx.pipeline().replace(decoderName, decoderName, new Socks5CommandResponseDecoder());
    sendToProxyServer(new DefaultSocks5CommandRequest(Socks5CommandType.CONNECT, addrType, rhost, raddr.getPort()));
}
 
Example 3
Source File: Endpoint.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static Endpoint create(String host, int port) {
    requireNonNull(host, "host");

    if (NetUtil.isValidIpV4Address(host)) {
        return new Endpoint(host, host, port, DEFAULT_WEIGHT, HostType.IPv4_ONLY);
    }

    if (NetUtil.isValidIpV6Address(host)) {
        final String ipV6Addr;
        if (host.charAt(0) == '[') {
            // Strip surrounding '[' and ']'.
            ipV6Addr = host.substring(1, host.length() - 1);
        } else {
            ipV6Addr = host;
        }
        return new Endpoint(ipV6Addr, ipV6Addr, port, DEFAULT_WEIGHT, HostType.IPv6_ONLY);
    }

    return new Endpoint(InternetDomainName.from(host).toString(),
                        null, port, DEFAULT_WEIGHT, HostType.HOSTNAME_ONLY);
}
 
Example 4
Source File: Socks4ClientEncoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, Socks4CommandRequest msg, ByteBuf out) throws Exception {
    out.writeByte(msg.version().byteValue());
    out.writeByte(msg.type().byteValue());
    out.writeShort(msg.dstPort());
    if (NetUtil.isValidIpV4Address(msg.dstAddr())) {
        out.writeBytes(NetUtil.createByteArrayFromIpAddressString(msg.dstAddr()));
        ByteBufUtil.writeAscii(out, msg.userId());
        out.writeByte(0);
    } else {
        out.writeBytes(IPv4_DOMAIN_MARKER);
        ByteBufUtil.writeAscii(out, msg.userId());
        out.writeByte(0);
        ByteBufUtil.writeAscii(out, msg.dstAddr());
        out.writeByte(0);
    }
}
 
Example 5
Source File: DefaultSocks4CommandResponse.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance.
 *
 * @param status the status of the response
 * @param dstAddr the {@code DSTIP} field of the response
 * @param dstPort the {@code DSTPORT} field of the response
 */
public DefaultSocks4CommandResponse(Socks4CommandStatus status, String dstAddr, int dstPort) {
    if (status == null) {
        throw new NullPointerException("cmdStatus");
    }
    if (dstAddr != null) {
        if (!NetUtil.isValidIpV4Address(dstAddr)) {
            throw new IllegalArgumentException(
                    "dstAddr: " + dstAddr + " (expected: a valid IPv4 address)");
        }
    }
    if (dstPort < 0 || dstPort > 65535) {
        throw new IllegalArgumentException("dstPort: " + dstPort + " (expected: 0~65535)");
    }

    this.status = status;
    this.dstAddr = dstAddr;
    this.dstPort = dstPort;
}
 
Example 6
Source File: NetUtilBenchmark.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Benchmark
public void useIsValidIpv4() {
    for (String host : invalidIpV4Hosts.keySet()) {
        if (NetUtil.isValidIpV4Address(host)) {
            throw new RuntimeException("error");
        }
    }
}
 
Example 7
Source File: InetAddressPredicates.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link Predicate} which returns {@code true} if the given {@link InetAddress} is in the
 * range of a <a href="https://tools.ietf.org/html/rfc4632">Classless Inter-domain Routing (CIDR)</a> block.
 *
 * @param cidr the CIDR notation of an address block, e.g. {@code 10.0.0.0/8}, {@code 192.168.1.0/24},
 *             {@code 1080:0:0:0:8:800:200C:4100/120}. If it's an exact IP address such as
 *             {@code 10.1.1.7} or {@code 1080:0:0:0:8:800:200C:4100}, the mask bits is considered as
 *             {@code 32} for IPv4 or {@code 128} for IPv6.
 */
public static Predicate<InetAddress> ofCidr(String cidr) {
    requireNonNull(cidr, "cidr");

    final int delim = cidr.indexOf('/');

    final InetAddress baseAddress;
    final int maskBits;
    try {
        // Exact IP address.
        if (delim < 0) {
            baseAddress = InetAddress.getByName(cidr);
            maskBits = baseAddress instanceof Inet4Address ? 32 : 128;
        } else {
            baseAddress = InetAddress.getByName(cidr.substring(0, delim));
            final String subnetMask = cidr.substring(delim + 1);
            checkArgument(!subnetMask.isEmpty(), "Invalid CIDR notation: %s", cidr);
            if (NetUtil.isValidIpV4Address(subnetMask)) {
                maskBits = toMaskBits(subnetMask);
                return ofCidr(baseAddress, maskBits, maskBits + 96);
            }
            maskBits = Integer.parseInt(subnetMask);
        }
    } catch (Exception e) {
        throw new IllegalArgumentException("Invalid CIDR notation: " + cidr, e);
    }
    return ofCidr(baseAddress, maskBits, maskBits);
}
 
Example 8
Source File: SocksCmdResponse.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs new response and includes provided host and port as part of it.
 *
 * @param cmdStatus status of the response
 * @param addressType type of host parameter
 * @param host host (BND.ADDR field) is address that server used when connecting to the target host.
 *             When null a value of 4/8 0x00 octets will be used for IPv4/IPv6 and a single 0x00 byte will be
 *             used for domain addressType. Value is converted to ASCII using {@link IDN#toASCII(String)}.
 * @param port port (BND.PORT field) that the server assigned to connect to the target host
 * @throws NullPointerException in case cmdStatus or addressType are missing
 * @throws IllegalArgumentException in case host or port cannot be validated
 * @see IDN#toASCII(String)
 */
public SocksCmdResponse(SocksCmdStatus cmdStatus, SocksAddressType addressType, String host, int port) {
    super(SocksResponseType.CMD);
    if (cmdStatus == null) {
        throw new NullPointerException("cmdStatus");
    }
    if (addressType == null) {
        throw new NullPointerException("addressType");
    }
    if (host != null) {
        switch (addressType) {
            case IPv4:
                if (!NetUtil.isValidIpV4Address(host)) {
                    throw new IllegalArgumentException(host + " is not a valid IPv4 address");
                }
                break;
            case DOMAIN:
                if (IDN.toASCII(host).length() > 255) {
                    throw new IllegalArgumentException(host + " IDN: " +
                            IDN.toASCII(host) + " exceeds 255 char limit");
                }
                break;
            case IPv6:
                if (!NetUtil.isValidIpV6Address(host)) {
                    throw new IllegalArgumentException(host + " is not a valid IPv6 address");
                }
                break;
            case UNKNOWN:
                break;
        }
        host = IDN.toASCII(host);
    }
    if (port < 0 || port > 65535) {
        throw new IllegalArgumentException(port + " is not in bounds 0 <= x <= 65535");
    }
    this.cmdStatus = cmdStatus;
    this.addressType = addressType;
    this.host = host;
    this.port = port;
}
 
Example 9
Source File: SocksCmdRequest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
public SocksCmdRequest(SocksCmdType cmdType, SocksAddressType addressType, String host, int port) {
    super(SocksRequestType.CMD);
    if (cmdType == null) {
        throw new NullPointerException("cmdType");
    }
    if (addressType == null) {
        throw new NullPointerException("addressType");
    }
    if (host == null) {
        throw new NullPointerException("host");
    }
    switch (addressType) {
        case IPv4:
            if (!NetUtil.isValidIpV4Address(host)) {
                throw new IllegalArgumentException(host + " is not a valid IPv4 address");
            }
            break;
        case DOMAIN:
            if (IDN.toASCII(host).length() > 255) {
                throw new IllegalArgumentException(host + " IDN: " + IDN.toASCII(host) + " exceeds 255 char limit");
            }
            break;
        case IPv6:
            if (!NetUtil.isValidIpV6Address(host)) {
                throw new IllegalArgumentException(host + " is not a valid IPv6 address");
            }
            break;
        case UNKNOWN:
            break;
    }
    if (port <= 0 || port >= 65536) {
        throw new IllegalArgumentException(port + " is not in bounds 0 < x < 65536");
    }
    this.cmdType = cmdType;
    this.addressType = addressType;
    this.host = IDN.toASCII(host);
    this.port = port;
}
 
Example 10
Source File: SSAddrRequest.java    From shadowsocks-java with MIT License 5 votes vote down vote up
public SSAddrRequest(SocksAddressType addressType, String host, int port) {
     if (addressType == null) {
        throw new NullPointerException("addressType");
    } else if (host == null) {
        throw new NullPointerException("host");
    } else {
        switch(addressType) {
            case IPv4:
                if (!NetUtil.isValidIpV4Address(host)) {
                    throw new IllegalArgumentException(host + " is not a valid IPv4 address");
                }
                break;
            case DOMAIN:
                if (IDN.toASCII(host).length() > 255) {
                    throw new IllegalArgumentException(host + " IDN: " + IDN.toASCII(host) + " exceeds 255 char limit");
                }
                break;
            case IPv6:
                if (!NetUtil.isValidIpV6Address(host)) {
                    throw new IllegalArgumentException(host + " is not a valid IPv6 address");
                }
            case UNKNOWN:
        }

        if (port > 0 && port < 65536) {
            this.addressType = addressType;
            this.host = IDN.toASCII(host);
            this.port = port;
        } else {
            throw new IllegalArgumentException(port + " is not in bounds 0 < x < 65536");
        }
    }
}
 
Example 11
Source File: SslUtils.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link SslHandler} which will supports SNI if the {@link InetSocketAddress} was created from
 * a hostname.
 *
 * @param context the {@link SslContext} which will be used to create the {@link SslHandler}
 * @param allocator the {@link ByteBufAllocator} which will be used to allocate direct memory if required for
 * {@link SSLEngine}
 * @param hostnameVerificationAlgorithm see {@link SSLParameters#setEndpointIdentificationAlgorithm(String)}.
 * If this is {@code null} or empty then you will be vulnerable to a MITM attack.
 * @param hostnameVerificationHost the non-authoritative name of the host.
 * @param hostnameVerificationPort the non-authoritative port.
 * @return a {@link SslHandler}
 */
static SslHandler newHandler(SslContext context, ByteBufAllocator allocator,
                             @Nullable String hostnameVerificationAlgorithm,
                             @Nullable String hostnameVerificationHost,
                             int hostnameVerificationPort) {
    if (hostnameVerificationHost == null) {
        return newHandler(context, allocator);
    }

    SslHandler handler = context.newHandler(allocator, hostnameVerificationHost, hostnameVerificationPort);
    SSLEngine engine = handler.engine();
    try {
        SSLParameters parameters = engine.getSSLParameters();
        parameters.setEndpointIdentificationAlgorithm(hostnameVerificationAlgorithm);
        if (!NetUtil.isValidIpV4Address(hostnameVerificationHost) &&
                !NetUtil.isValidIpV6Address(hostnameVerificationHost)) {
            // SNI doesn't permit IP addresses!
            // https://tools.ietf.org/html/rfc6066#section-3
            // Literal IPv4 and IPv6 addresses are not permitted in "HostName".
            parameters.setServerNames(Collections.singletonList(new SNIHostName(hostnameVerificationHost)));
        }
        engine.setSSLParameters(parameters);
    } catch (Throwable cause) {
        ReferenceCountUtil.release(engine);
        throw cause;
    }
    return handler;
}
 
Example 12
Source File: DefaultSocks5CommandResponse.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public DefaultSocks5CommandResponse(
        Socks5CommandStatus status, Socks5AddressType bndAddrType, String bndAddr, int bndPort) {

    if (status == null) {
        throw new NullPointerException("status");
    }
    if (bndAddrType == null) {
        throw new NullPointerException("bndAddrType");
    }
    if (bndAddr != null) {
        if (bndAddrType == Socks5AddressType.IPv4) {
            if (!NetUtil.isValidIpV4Address(bndAddr)) {
                throw new IllegalArgumentException("bndAddr: " + bndAddr + " (expected: a valid IPv4 address)");
            }
        } else if (bndAddrType == Socks5AddressType.DOMAIN) {
            bndAddr = IDN.toASCII(bndAddr);
            if (bndAddr.length() > 255) {
                throw new IllegalArgumentException("bndAddr: " + bndAddr + " (expected: less than 256 chars)");
            }
        } else if (bndAddrType == Socks5AddressType.IPv6) {
            if (!NetUtil.isValidIpV6Address(bndAddr)) {
                throw new IllegalArgumentException("bndAddr: " + bndAddr + " (expected: a valid IPv6 address)");
            }
        }
    }

    if (bndPort < 0 || bndPort > 65535) {
        throw new IllegalArgumentException("bndPort: " + bndPort + " (expected: 0~65535)");
    }
    this.status = status;
    this.bndAddrType = bndAddrType;
    this.bndAddr = bndAddr;
    this.bndPort = bndPort;
}
 
Example 13
Source File: DefaultSocks5CommandRequest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public DefaultSocks5CommandRequest(
        Socks5CommandType type, Socks5AddressType dstAddrType, String dstAddr, int dstPort) {

    if (type == null) {
        throw new NullPointerException("type");
    }
    if (dstAddrType == null) {
        throw new NullPointerException("dstAddrType");
    }
    if (dstAddr == null) {
        throw new NullPointerException("dstAddr");
    }

    if (dstAddrType == Socks5AddressType.IPv4) {
        if (!NetUtil.isValidIpV4Address(dstAddr)) {
            throw new IllegalArgumentException("dstAddr: " + dstAddr + " (expected: a valid IPv4 address)");
        }
    } else if (dstAddrType == Socks5AddressType.DOMAIN) {
        dstAddr = IDN.toASCII(dstAddr);
        if (dstAddr.length() > 255) {
            throw new IllegalArgumentException("dstAddr: " + dstAddr + " (expected: less than 256 chars)");
        }
    } else if (dstAddrType == Socks5AddressType.IPv6) {
        if (!NetUtil.isValidIpV6Address(dstAddr)) {
            throw new IllegalArgumentException("dstAddr: " + dstAddr + " (expected: a valid IPv6 address");
        }
    }

    if (dstPort < 0 || dstPort > 65535) {
        throw new IllegalArgumentException("dstPort: " + dstPort + " (expected: 0~65535)");
    }

    this.type = type;
    this.dstAddrType = dstAddrType;
    this.dstAddr = dstAddr;
    this.dstPort = dstPort;
}
 
Example 14
Source File: SocksCmdResponse.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs new response and includes provided host and port as part of it.
 *
 * @param cmdStatus status of the response
 * @param addressType type of host parameter
 * @param host host (BND.ADDR field) is address that server used when connecting to the target host.
 *             When null a value of 4/8 0x00 octets will be used for IPv4/IPv6 and a single 0x00 byte will be
 *             used for domain addressType. Value is converted to ASCII using {@link IDN#toASCII(String)}.
 * @param port port (BND.PORT field) that the server assigned to connect to the target host
 * @throws NullPointerException in case cmdStatus or addressType are missing
 * @throws IllegalArgumentException in case host or port cannot be validated
 * @see IDN#toASCII(String)
 */
public SocksCmdResponse(SocksCmdStatus cmdStatus, SocksAddressType addressType, String host, int port) {
    super(SocksResponseType.CMD);
    if (cmdStatus == null) {
        throw new NullPointerException("cmdStatus");
    }
    if (addressType == null) {
        throw new NullPointerException("addressType");
    }
    if (host != null) {
        switch (addressType) {
            case IPv4:
                if (!NetUtil.isValidIpV4Address(host)) {
                    throw new IllegalArgumentException(host + " is not a valid IPv4 address");
                }
                break;
            case DOMAIN:
                String asciiHost = IDN.toASCII(host);
                if (asciiHost.length() > 255) {
                    throw new IllegalArgumentException(host + " IDN: " + asciiHost + " exceeds 255 char limit");
                }
                host = asciiHost;
                break;
            case IPv6:
                if (!NetUtil.isValidIpV6Address(host)) {
                    throw new IllegalArgumentException(host + " is not a valid IPv6 address");
                }
                break;
            case UNKNOWN:
                break;
        }
    }
    if (port < 0 || port > 65535) {
        throw new IllegalArgumentException(port + " is not in bounds 0 <= x <= 65535");
    }
    this.cmdStatus = cmdStatus;
    this.addressType = addressType;
    this.host = host;
    this.port = port;
}
 
Example 15
Source File: SocksCmdRequest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public SocksCmdRequest(SocksCmdType cmdType, SocksAddressType addressType, String host, int port) {
    super(SocksRequestType.CMD);
    if (cmdType == null) {
        throw new NullPointerException("cmdType");
    }
    if (addressType == null) {
        throw new NullPointerException("addressType");
    }
    if (host == null) {
        throw new NullPointerException("host");
    }
    switch (addressType) {
        case IPv4:
            if (!NetUtil.isValidIpV4Address(host)) {
                throw new IllegalArgumentException(host + " is not a valid IPv4 address");
            }
            break;
        case DOMAIN:
            String asciiHost = IDN.toASCII(host);
            if (asciiHost.length() > 255) {
                throw new IllegalArgumentException(host + " IDN: " + asciiHost + " exceeds 255 char limit");
            }
            host = asciiHost;
            break;
        case IPv6:
            if (!NetUtil.isValidIpV6Address(host)) {
                throw new IllegalArgumentException(host + " is not a valid IPv6 address");
            }
            break;
        case UNKNOWN:
            break;
    }
    if (port <= 0 || port >= 65536) {
        throw new IllegalArgumentException(port + " is not in bounds 0 < x < 65536");
    }
    this.cmdType = cmdType;
    this.addressType = addressType;
    this.host = host;
    this.port = port;
}
 
Example 16
Source File: HAProxyMessage.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Validate an address (IPv4, IPv6, Unix Socket)
 *
 * @param address                    human-readable address
 * @param addrFamily                 the {@link AddressFamily} to check the address against
 * @throws HAProxyProtocolException  if the address is invalid
 */
private static void checkAddress(String address, AddressFamily addrFamily) {
    if (addrFamily == null) {
        throw new NullPointerException("addrFamily");
    }

    switch (addrFamily) {
        case AF_UNSPEC:
            if (address != null) {
                throw new HAProxyProtocolException("unable to validate an AF_UNSPEC address: " + address);
            }
            return;
        case AF_UNIX:
            return;
    }

    if (address == null) {
        throw new NullPointerException("address");
    }

    switch (addrFamily) {
        case AF_IPv4:
            if (!NetUtil.isValidIpV4Address(address)) {
                throw new HAProxyProtocolException("invalid IPv4 address: " + address);
            }
            break;
        case AF_IPv6:
            if (!NetUtil.isValidIpV6Address(address)) {
                throw new HAProxyProtocolException("invalid IPv6 address: " + address);
            }
            break;
        default:
            throw new Error();
    }
}
 
Example 17
Source File: IsValidIpV4Benchmark.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Benchmark
public boolean isValidIpV4AddressNew() {
    return NetUtil.isValidIpV4Address(ip);
}
 
Example 18
Source File: TestDnsServer.java    From armeria with Apache License 2.0 4 votes vote down vote up
public static DnsRecord newAddressRecord(String name, String ipAddr, long ttl) {
    return new DefaultDnsRawRecord(
            name, NetUtil.isValidIpV4Address(ipAddr) ? A : AAAA,
            ttl, Unpooled.wrappedBuffer(NetUtil.createByteArrayFromIpAddressString(ipAddr)));
}
 
Example 19
Source File: InstanceInfoBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static void validateIpAddr(String ipAddr, String name) {
    if (!NetUtil.isValidIpV4Address(ipAddr) && !NetUtil.isValidIpV6Address(ipAddr)) {
        throw new IllegalArgumentException("Invalid " + name + ": " + ipAddr);
    }
}