Java判断本机IP地址类型(第一版)

 1 package net;
 2 
 3 import java.net.*;
 4 
 5 /*
 6  *  getAddress方法和getHostAddress类似,它们的唯一区别是getHostAddress方法返回的是字符串形式的IP地址,
 7  *  而getAddress方法返回的是byte数组形式的IP地址。
 8  *  Java中byte类型的取值范围是-128?127。如果返回的IP地址的某个字节是大于127的整数,在byte数组中就是负数。
 9  *  由于Java中没有无符号byte类型,因此,要想显示正常的IP地址,必须使用int或long类型。
10  */
11 public class MyIp
12 {
13     /*
14      * ipv6共8段
15      */
16     public static void main(String[] args) throws Exception
17     {
18        // InetAddress ia = InetAddress.getByName("www.cnblogs.com");
19         InetAddress ia = InetAddress.getLocalHost();//本地主机的 IP 地址
20         //System.out.println(ia);
21         //byte ip[] = ia.getAddress();
22         /*
23         for (byte part : ip)
24             System.out.print(part + " ");
25         System.out.println("");
26         for (byte part : ip)
27         {
28             int newIp = (part < 0) ? 256 + part : part;
29             System.out.print(newIp + " ");
30         }
31         */
32         
33        /* int[] array = new int[5];
34         for(int i=0; i<ip.length; i++) {
35             array[i] = (ip[i] < 0) ? 256 + ip[i]  : ip[i];
36             
37         }*/
38         //通过判断ip地址中点号(不是冒号)的来划分ip字符串,根据字符串长度判断是ipv4还是ipv6
39         String ip = ia.getHostAddress();//没有返回主机名
40         System.out.println(ip);
41         //String str[] = new String[10];
42         String str[] = ip.split("\\.");//由于"."是regex的字符,所以需要转义
43         //System.out.println(str.length);
44         int num = Ipv4OrIpv6(str);
45         if(num==4) {
46             System.out.println("本机IP是IPV4类型");
47             int temp = Integer.valueOf(str[0]);
48             String s = TellIpType(temp);
49             System.out.println("属于" + s + "类IP地址!");
50         }
51         else {
52             System.out.println("本机IP是IPV6类型");
53         }
54         
55     }
56     /*
57      * 根据第一个字节判断IP地址类型
58      */
59     public static String TellIpType(int num) {
60         if(num<127)
61             return "A";
62         else if(num<192)
63             return "B";
64         else if(num<224)
65             return "C";
66         else if(num<240)
67             return "D";
68         else
69             return "E";
70     }
71     //
72     public static int Ipv4OrIpv6(String s[]) {
73         int num = 0;
74         return s.length;
75     }
76     
77 }
原文地址:https://www.cnblogs.com/hxsyl/p/2954756.html