Java设置Linux外网出口ip

最近爬虫项目中被封,服务器上绑定了多个ip,就想着怎样才能把多个ip都利用起来,想过设置成代理服务器的想法,但是由于某些原因放弃,所以采用动态改变服务器出口ip的方式将多个ip利用起来。

首先获取服务器绑定的ip

public static void getLocalIps(){
	try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            String name = intf.getName();
            if (!name.contains("docker") && !name.contains("lo")) {
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String ipaddress = inetAddress.getHostAddress().toString();
                        if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                            localIps.add(ipaddress);
                        }
                    }
                }
            }
        }
    } catch (SocketException ex) {
        System.out.println("获取ip地址异常");
        ex.printStackTrace();
    }
}

 

编写切换linux出口ip的脚本

#!/bin/sh
iptables -t nat -I POSTROUTING -o eth0 -d 0.0.0.0/0 -s 192.168.0.1 -j SNAT --to-source $1

 

使用java调用shell脚本,切换出口ip

public static void setOutIp(){
    for (String ip : localIps) {
        try {
            Runtime.getRuntime().exec(ApplicationConfig.prop.getProperty("ipshell")+" "+ip);
            logger.info("设置出口ip:"+ip);
            if(checkIpCanUsed(null, null)){//查看ip是否可用
                return;
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }
}

 

附:查看linux出口ip的方法

 

curl icanhazip.com
curl ifconfig.me
curl curlmyip.com
curl ip.appspot.com
curl ipinfo.io/ip
curl ipecho.net/plain
curl www.trackip.net/i

本文由微儿博客原创,博客地址:www.weare.net.cn 或者点击 微儿博客

猜你喜欢

转载自weareweier.iteye.com/blog/2352685
今日推荐