在线运行Java代码获取APNIC中国区的ip段,用作绕过国内ip

如题,不废话了,直接上java代码。这个获取的IP段是最新的国内IP段。

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Description
 * Date: 2019/6/12 15:32
 * Created by jonhy_love
 */
class GetAPNIC {
    public static void main(String []args) {
        Map map = request("http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest");
        System.out.println(parseOnline(map.get("result")));
    }


    /**
     * 在线解析
     * @param str1
     * @return
     */
    private static String parseOnline(String str1){
       String lists[] = str1.split("\n");
        StringBuilder sb = new StringBuilder();
        try {
            for (String str:lists) {
                if (str.startsWith("apnic") && str.contains("|CN|ipv4|")){
                    String a[] = str.split("\\|");
                    Integer mask = 32-(int)(Math.log(Double.valueOf(a[4]))/Math.log(2));
                    sb.append(a[3]).append("/").append(mask).append('\n');
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    private static Map request(String url) {
        Map response = new HashMap();
        try{
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            //设置请求方式
            con.setRequestMethod("GET");
            con.setDoOutput(true);
            int responseCode = con.getResponseCode();
            response.put("code",responseCode + "");
            if (responseCode == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer responseBuffer = new StringBuffer();
                while((inputLine = in.readLine())!=null){
                    responseBuffer.append(inputLine).append("\n");
                }
                in.close();
                response.put("result",responseBuffer.toString());
            }else{
                response.put("result","");
            }
        }catch (Exception e){
            response.put("result","failed");
        }
        return response;
    }
}

将上述代码复制到剪辑版,进入在线运行网站:http://www.dooccn.com/java/

粘贴代码,点击run即可。

效果如下:

在线运行Java代码获取APNIC中国区的ip段,用作绕过国内ip_第1张图片

 

这样就可以随时方便在线获取国内IP段用作路由规则了。

 

 

参考来源:

代码在线运行网站 

https://blog.csdn.net/u014549283/article/details/81780992

Apnic IP地址段的获取与整理方法介绍

https://blog.csdn.net/nullzeng/article/details/17538009

你可能感兴趣的:(网络杂项)