当前位置: 移动技术网 > IT编程>开发语言>Java > Java判断本机IP地址类型的方法

Java判断本机IP地址类型的方法

2019年07月22日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下:

   package net;

 import java.net.*;

 /*
  *  getaddress方法和gethostaddress类似,它们的唯一区别是gethostaddress方法返回的是字符串形式的ip地址,
  *  而getaddress方法返回的是byte数组形式的ip地址。
  *  java中byte类型的取值范围是-128?127。如果返回的ip地址的某个字节是大于127的整数,在byte数组中就是负数。
  *  由于java中没有无符号byte类型,因此,要想显示正常的ip地址,必须使用int或long类型。
  */
 public class myip
 {
     public static void main(string[] args) throws exception
     {
         inetaddress ia = inetaddress.getbyname("www.cnblogs.com");
         byte ip[] = ia.getaddress();
         /*
         for (byte part : ip)
             system.out.print(part + " ");
         system.out.println("");
         for (byte part : ip)
         {
             int newip = (part < 0) ? 256 + part : part;
             system.out.print(newip + " ");
         }
         */
         int[] array = new int[5];
         for(int i=0; i<ip.length; i++) {
             array[i] = (ip[i] < 0) ? 256 + ip[i]  : ip[i];

         }
         string str = telliptype(array[0]);
         system.out.println(str);

        
     }
     /*
      * 根据第一个字节判断ip地址类型
      */
     public static string telliptype(int num) {
         if(num<127)
             return "a";
         else if(num<192)
             return "b";
         else if(num<224)
             return "c";
         else if(num<240)
             return "d";
         else
             return "e";
     }
 }
  

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网