java 判定1个IP地址是否是合法IP
生活随笔
收集整理的這篇文章主要介紹了
java 判定1个IP地址是否是合法IP
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
測試使用工具:Eclipse
工具使用截圖:
編寫思路:
IP地址判定函數
package ipJudge;public class IPJudge {public static boolean isRightIP (String ip){//排除空值if(ip == null){ return false;}//基于IP地址長度進行排除if(ip.length()<7 || ip.length()>15){ return false;}//避免Integer.parseInt轉換時報錯,大家也可以注銷如下的if代碼調試。if(ip.charAt(0) == '.' || ip.charAt(ip.length()-1) == '.' ){return false;}String[] Inip= ip.split("\\.");if (Inip.length != 4){return false;}//判斷所有的字符是否均是數字for(int i=0;i<4;i++){for(int j=0;j<Inip[i].length();j++){if(Inip[i].charAt(j) < '0' || Inip[i].charAt(j) > '9'){return false;}}}//IP范圍進行判斷(0.0.0.0-255.255.255.255)for(int i=0;i < Inip.length;i++){int temp = Integer.parseInt(Inip[i]);if(temp < 0 || temp > 255){return false;}} return true;} }測試代碼
package file; import ipJudge.IPJudge;import java.util.ArrayList; import java.util.List; import java.io.*;public class FileRW {public static void main(String[] args){File file = new File("E:\\JAVA_storage\\IP測試\\IP.txt");File fnew = new File("E:\\JAVA_storage\\IP測試\\IP驗證結果.txt");//文本中IP地址讀入FileWriter fwrite=null;BufferedReader reader = null;List<String> list = new ArrayList<>();try {reader = new BufferedReader(new FileReader(file));String tempString =null;while ((tempString = reader.readLine()) != null){list.add(tempString);}reader.close();//IP地址測試結果輸出到文本中fwrite = new FileWriter(fnew);StringBuffer write = new StringBuffer();for(String tmpIP : list){//調用IPjudge中IP的判定方法函數boolean right = IPJudge.isRightIP(tmpIP);System.out.println(right + ", ip: " + tmpIP);write.append(right + ", ip: " + tmpIP + "\n");}fwrite.write(write.toString());fwrite.flush();}catch (IOException e){e.printStackTrace();}finally{if(fwrite != null){try {fwrite.close();} catch (IOException e) {System.out.println(e);}}}}}IP地址測試文本
0.0.0.0 255.255.255.255 12.25.35.69 255.213.23.12 1 1.22.2.23 12323.1232.2323.12323 s.23.32.12 12.e.2.3 1.3.*.4 12.243.23.!!? e/.RT.45.2 a.d.@.4 !?.d.feewfe.se 12.we2.12 12.3.2 12.34 12 wer2e .32.12.23 12.23.4. \\.dsf.22.dsf2 wwwwwwwwwwwwwwwwwwwwwwwwwwwwww.22222222222222222222222.2222222222222222222.33333333333333IP地址測試結果文本查看
true, ip: 0.0.0.0 true, ip: 255.255.255.255 true, ip: 12.25.35.69 true, ip: 255.213.23.12 false, ip: 1 1.22.2.23 false, ip: 12323.1232.2323.12323 false, ip: s.23.32.12 false, ip: 12.e.2.3 false, ip: 1.3.*.4 false, ip: 12.243.23.!!? false, ip: e/.RT.45.2 false, ip: a.d.@.4 false, ip: !?.d.feewfe.se false, ip: 12.we2.12 false, ip: 12.3.2 false, ip: 12.34 false, ip: 12 false, ip: wer2e false, ip: .32.12.23 false, ip: 12.23.4. false, ip: \\.dsf.22.dsf2 false, ip: wwwwwwwwwwwwwwwwwwwwwwwwwwwwww.22222222222222222222222.2222222222222222222.33333333333333?
總結
以上是生活随笔為你收集整理的java 判定1个IP地址是否是合法IP的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 更改虚拟机centos7的系统时间
- 下一篇: 第二次作业+105032014101