验证IP和HostName

来源:互联网 发布:linux vi退出保存 编辑:程序博客网 时间:2024/06/07 19:10
项目需要对输入的某值进行校验,该值可能是IP,也可能是HOSTNAME。
对于IP,可以简单的用JDK提供的方法进行校验:

try { InetAddress.getByName(ip);} catch (UnknownHostException uhe) { throw new Exception("Ip address " +ip + " is invalid!");}

getByName方法原本是传入host name,解析成IP返回,但是也支持传入IP,返回IP,同时对该IP做了校验。

对于HOSTNAME,就比较麻烦点,得用正则表达式:
这里顺便把校验IPV4和V6的REG也写出来:

public static String REG_IPV4 = "\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}\\b"; public static String REG_IPV6 = "^(((?=(?>.*?::)(?!.*::)))(::)?([0-9A-F]{1,4}::?){0,5}|([0-9A-F]{1,4}:){6})(\\2([0-9A-F]{1,4}(::?|$)){0,2}|((25[0-5]|(2[0-4]|1\\d|[1-9])?\\d)(\\.|$)){4}|[0-9A-F]{1,4}:[0-9A-F]{1,4})(?<![^:]:|\\.)\\z";

public static String VALID_HOST_REGEX = "^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|\\b-){0,61}[0-9A-Za-z])?(?:\\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|\\b-){0,61}[0-9A-Za-z])?)*\\.?$";

用的时候很简单:

Pattern pattern = Pattern.compile(VALID_HOST_REGEX, Pattern.CASE_INSENSITIVE);Matcher matcher = pattern.matcher(host); if(!matcher.find()){

throw new Exception("Invalid gateway host");}



PS:
附上参考网站:
http://www.intermapper.com/ipv6validator
它的脚本页里面提供了大量的IPV6的测试用例:
http://download.dartware.com/thirdparty/test-ipv6-regex.pl

另一个验证IPV6的:http://www.mebsd.com/coding-snipits/php-regex-ipv6-with-preg_match-revisited.html
原创粉丝点击