使用hutu的NetUtil判断IP为内网

x33g5p2x  于2022-04-01 转载在 其他  
字(1.6k)|赞(0)|评价(0)|浏览(403)

之前写过一篇是关于怎么区分内网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));
 }
}

可以使用很简短的包代替之前方法。

相关文章