Java设置Linux外网出口ip
2017-01-12 17:25
162 查看
最近爬虫项目中被封,服务器上绑定了多个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 或者点击 微儿博客
相关文章推荐
- java设置Linux外网出口ip
- linux下查看外网出口IP
- 详解几种Linux 查询外网出口IP命令的方法
- 几种Linux 查询外网出口IP的方法
- 几种Linux 查询外网出口IP的方法(转)
- 几种Linux 查询外网出口IP的方法
- linux查看外网出口IP
- 虚拟机里面linux设置固定IP,访问外网
- linux下查看外网出口IP
- linux设置好IP后,可以访问内网,不能访问外网
- linux获取本机出口外网IP
- Linux 设置IP、添加权限、设置java环境变量、设置网络时间、图形界面转换成命令行
- 几种Linux 查询外网出口IP的方法
- linux: centos设置ip以及连接外网的方法
- 虚拟机下linux red hat 6.8设置静态固定IP、网关及ping通外网
- Linux环境下java后台获取外网IP
- linux: centos设置ip以及连接外网
- [Linux]在Linux上部署Java开发环境笔记(一)-- 补充:Linux下如何手动设置IP及配置DNS服务
- linux下程序设计-IP获取与设置