之前写过一篇是关于怎么区分内网IP的方法,方法如下:
import java.util.regex.Pattern
object IpUtils {
private fun ipv4Address2BinaryArray(ipAdd: String): ByteArray {
val binIP = ByteArray(4)
val strArray = ipAdd.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (i in strArray.indices) {
binIP[i] = strArray[i].toInt().toByte()
}
return binIP
}
fun internalIp(ipAddress: String): Boolean {
if(!isIpV4(ipAddress)){
return false
}
val address: ByteArray = ipv4Address2BinaryArray(ipAddress)
val b0 = address[0]
val b1 = address[1]
val SECTION_1: Byte = 0x0A
val SECTION_2 = 0xAC.toByte()
val SECTION_3 = 0x10.toByte()
val SECTION_4 = 0x1F.toByte()
val SECTION_5 = 0xC0.toByte()
val SECTION_6 = 0xA8.toByte()
return when (b0) {
SECTION_1 -> true
SECTION_2 -> {
return b1 in SECTION_3..SECTION_4
}
SECTION_5 -> {
b1 == SECTION_6
}
else -> false
}
}
fun isIpV4(ipAddress:String):Boolean{
val ipv4="([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}"
return Pattern.compile(ipv4).matcher(ipAddress).matches()
}
}
现在使用hutu的netUtil和netty的
public class IPTest {
public static void main(String[] args) {
String ipAddress="202.168.2.12";
System.out.println(io.netty.util.NetUtil.isValidIpV4Address(ipAddress));
System.out.println(cn.hutool.core.net.NetUtil.isInnerIP(ipAddress));
}
}
可以使用很简短的包代替之前方法。
|