之前写过一篇是关于怎么区分内网IP的方法,方法如下:
import java.util.regex.Pattern
/**
* @program: fs-resource-usage
* @description: IpUtils
* @author: sunyuhua
* @create: 2022-03-29 12:13
**/
object IpUtils {
/**
* 将string转化为byte[]
* @param ipAdd
* @return
*/
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
}
/**
* 判断Ip v4 是不是内网IP
*/
fun internalIp(ipAddress: String): Boolean {
//任何不合法的字符,直接返回false
if(!isIpV4(ipAddress)){
return false
}
val address: ByteArray = ipv4Address2BinaryArray(ipAddress)
val b0 = address[0]
val b1 = address[1]
//10.x.x.x/8
val SECTION_1: Byte = 0x0A
//172.16.x.x/12
val SECTION_2 = 0xAC.toByte()
val SECTION_3 = 0x10.toByte()
val SECTION_4 = 0x1F.toByte()
//192.168.x.x/16
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的
/**
* @program: javademo
* @description:
* @author: sunyuhua
* @create: 2022-03-31 11:23
**/
public class IPTest {
public static void main(String[] args) {
//String ipAddress="-";
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));
}
}
可以使用很简短的包代替之前方法。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/sunyuhua_keyboard/article/details/123866743
内容来源于网络,如有侵权,请联系作者删除!