簡體   English   中英

如何將 IP 地址范圍轉換為正則表達式?

[英]How to convert an IP address range to Regex?

我想配置 tomcat internalProxies遠程 IP 閥門以信任Google GFE 源地址

  • 35.191.0.0/16
  • 130.211.0.0/22

Tomcat 只接受這些值的正則表達式。

  • 將 ip 地址范圍轉換為 java.util.Regex 的公式是什么?
  • 是否有任何工具可以將 ip 地址范圍轉換為正則表達式?

我在這里找到了這個工具。 如果您刪除反斜杠\之前. 在提供的正則表達式似乎與java.util.regex.Pattern兼容。

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class IPMatchTester {

     public static void main(String []args){
         // For 35.191.0.0/16
         Pattern p = Pattern.compile("^(35.191.(?:[0-9]|[1-9][0-9]|1(?:[0-9][0-9])|2(?:[0-4][0-9]|5[0-5])).(?:[0-9]|[1-9][0-9]|1(?:[0-9][0-9])|2(?:[0-4][0-9]|5[0-5])))$");
         int matchCount = 0;
         for( int j = 0; j <= 255; j++){
             for( int i = 0; i <= 255; i++){
                 if(!p.matcher("35.191."+ j +"." +i ).matches()){
                     System.out.println("35.191." + j + "."+ i + " no matched ");
                 } else{
                     matchCount++;
                 }
             }
         }
         System.out.println("Number of ip matched: " + matchCount);
         
         
         // For 130.211.0.0/22
         Pattern p2 = Pattern.compile("^(130.211.(?:[0-3]).(?:[0-9]|[1-9][0-9]|1(?:[0-9][0-9])|2(?:[0-4][0-9]|5[0-5])))$");
         int matchCount2 = 0;
         for( int j = 0; j <= 3; j++){
             for( int i = 0; i <=255; i++){
                 if(!p2.matcher("130.211."+ j +"." +i ).matches()){
                     System.out.println("130.211." + j + "."+ i + " no matched ");
                 } else{
                     matchCount2++;
                 }
             }
         }
         System.out.println("Number of ip matched: " + matchCount2);
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM