首页 > 其他分享 >验证IP地址

验证IP地址

时间:2022-11-10 23:11:08浏览次数:45  
标签:tmp return subs 验证 IP IP地址 Neither

 

import java.util.*;

public class Solution {     /**      * 验证IP地址      * @param IP string字符串 一个IP地址字符串      * @return string字符串      */     public String solve (String IP) {         //判断可能是IPV4,子串转化为数字,范围是否在0-255,且不以为0开始         //判断可能是IPV6,判断子串是否匹配[0-9a-fA-F],是否最多4位,是否有多余的0         //既不是IPV4,又不是IPV6         if(IP.indexOf(".")!=-1){             String[] subs = IP.split("\\.");             if(subs.length!=4){                 return "Neither";             }             for(int i=0; i<4; i++){                 if(!subs[i].matches("[0-9]*")){                     return "Neither";                 }                 if(subs[i].startsWith("0")){                     return "Neither";                 }                 int tmp = Integer.parseInt(subs[i]);                 if(tmp>255 || tmp<=0 ){                     return "Neither";                 }                  if(i==3){                     return "IPv4";                 }             }         }         else if(IP.indexOf(":")!=-1){             String[] subs = IP.split(":");             if(subs.length!=8 ||IP.endsWith(":")){                 return "Neither";             }             for(int i=0; i<8; i++){                 if(!subs[i].matches("[0-9a-fA-F]*")){                     return "Neither";                 }                 if(subs[i].length()>4){                     return "Neither";                 }                 if(subs[i].startsWith("00")|| subs[i].startsWith("000")|| subs[i].startsWith("0000")){                     return "Neither";                 }                 if(subs[i].equals("")){                     return "Neither";                 }                 int tmp = Integer.parseInt(subs[i],16);                 if(tmp>65535 || tmp<0 ){                     return "Neither";                 }                  if(i==7){                     return "IPv6";                 }             }
        }else{             return "Neither";         }         return "Neither";     } }

 

标签:tmp,return,subs,验证,IP,IP地址,Neither
From: https://www.cnblogs.com/northli/p/16879170.html

相关文章