• Java判断IP地址类型(第二版)


     1 import java.net.Inet4Address;
     2 import java.net.Inet6Address;
     3 import java.net.InetAddress;
     4 import java.net.UnknownHostException;
     5 
     6 /*
     7  * 第一版判断Ipv4或者Ipv6是通过是通过长度来实现的(4段为Ipv4,16段是Ipv6),由于判断的是本机IP,
     8  * 所以没有校验值得合法性;
     9  * 后来学了正则表达式;
    10  * 现在使用instanceof操作符。
    11  */
    12 public class TestIP {
    13 
    14     public static void main(String[] args) throws UnknownHostException {
    15         // TODO Auto-generated method stub
    16         /*
    17          * 老师说了getByName已经根据地址类型返回Inet4Address或者Inet6Address
    18          * 所以直接使用instanceof;
    19          * 原来发现有问题,结果改成了Object ia = (Object)InetAddress.getByName("www.baidu.com")对了,
    20          * 后来发现忘记引入包了Inet4Address和Inet6Address.
    21          */
    22         InetAddress ia = InetAddress.getByName("www.baidu.com");
    23         System.out.println(ia);
    24         
    25         boolean flag1 = ia instanceof Inet4Address;
    26         boolean flag2 = ia instanceof Inet6Address;
    27         
    28         if(flag1) {
    29             System.out.println("IPV4地址");
    30             System.out.println("根据第一字节判断类别(A到E)!");
    31         }else if(flag2) {
    32             System.out.println("IPV6地址");
    33         }else {
    34             System.out.println("非法IP");//若是发生UnknownHostException则该句有效
    35         }
    36     }
    37 
    38 }
  • 相关阅读:
    AGC 015 E
    CF 1041 F. Ray in the tube
    AGC 005 D
    CF 348 D. Turtles
    2069: [POI2004]ZAW
    AGC 007 D
    zhengruioi 470 区间
    2653: middle
    Django 源码安装及使用
    Django MTV模型思想
  • 原文地址:https://www.cnblogs.com/hxsyl/p/2981534.html
Copyright © 2020-2023  润新知