package io.undertow.util;
import io.undertow.UndertowMessages;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
public class NetworkUtils {
public static String formatPossibleIpv6Address(String address) {
if (address == null) {
return null;
}
if (!address.contains(":")) {
return address;
}
if (address.startsWith("[") && address.endsWith("]")) {
return address;
}
return "[" + address + "]";
}
public static InetAddress parseIpv4Address(String addressString) throws IOException {
String[] parts = addressString.split("\\.");
if (parts.length != 4) {
throw UndertowMessages.MESSAGES.invalidIpAddress(addressString);
}
byte[] data = new byte[4];
for (int i = 0; i < 4; ++i) {
String part = parts[i];
if (part.length() == 0 || (part.charAt(0) == '0' && part.length() > 1)) {
throw UndertowMessages.MESSAGES.invalidIpAddress(addressString);
}
data[i] = (byte) Integer.parseInt(part);
}
return InetAddress.getByAddress(data);
}
public static InetAddress parseIpv6Address(String addressString) throws IOException {
boolean startsWithColon = addressString.startsWith(":");
if (startsWithColon && !addressString.startsWith("::")) {
throw UndertowMessages.MESSAGES.invalidIpAddress(addressString);
}
String[] parts = (startsWithColon ? addressString.substring(1) : addressString).split(":");
byte[] data = new byte[16];
int partOffset = 0;
boolean seenEmpty = false;
if (parts.length > 8) {
throw UndertowMessages.MESSAGES.invalidIpAddress(addressString);
}
for (int i = 0; i < parts.length; ++i) {
String part = parts[i];
if (part.length() > 4) {
throw UndertowMessages.MESSAGES.invalidIpAddress(addressString);
} else if (part.isEmpty()) {
if (seenEmpty) {
throw UndertowMessages.MESSAGES.invalidIpAddress(addressString);
}
seenEmpty = true;
int off = 8 - parts.length;
if (off < 0) {
throw UndertowMessages.MESSAGES.invalidIpAddress(addressString);
}
partOffset = off * 2;
} else if (part.length() > 1 && part.charAt(0) == '0') {
throw UndertowMessages.MESSAGES.invalidIpAddress(addressString);
} else {
int num = Integer.parseInt(part, 16);
data[i * 2 + partOffset] = (byte) (num >> 8);
data[i * 2 + partOffset + 1] = (byte) (num);
}
}
if (parts.length < 8 && !seenEmpty) {
throw UndertowMessages.MESSAGES.invalidIpAddress(addressString);
}
return InetAddress.getByAddress(data);
}
public static String toObfuscatedString(InetAddress address) {
if (address == null) {
return null;
}
String s = address.getHostAddress();
if (address instanceof Inet4Address) {
return s.substring(0, s.lastIndexOf(".")+1);
}
return s.substring(0, s.indexOf(":", s.indexOf(":")+1)+1);
}
private NetworkUtils() {
}
}