feat[util]: ip to long of ipv4 or ipv6

This commit is contained in:
godotg
2023-05-07 14:23:16 +08:00
parent a4538f4719
commit f382c21c3e
@@ -21,6 +21,7 @@ import org.springframework.lang.Nullable;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.*;
import java.util.*;
import java.util.regex.Pattern;
@@ -102,6 +103,18 @@ public class NetUtils {
return IPV4.matcher(address).matches() || IPV6.matcher(address).matches();
}
// 同时支持ipv4和ipv6
public static long ipToLong(String ip) {
try {
var inetAddress = InetAddress.getByName(ip);
var ipAddress = inetAddress.getAddress();
var ipBigInt = new BigInteger(1, ipAddress);
return ipBigInt.longValue();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 检测本地端口可用性<br>
* 来自org.springframework.util.SocketUtils