本周因为工作需要,需要获取服务器对应的出口ip,这里对获取方式做一下记录。
Linux下如何获取机器的出口IP
这里机器都可以访问到外网情况下,否则的话获取出口IP就没有什么意义了。
方式一
curl cip.cc
IP : 111.xxx.xxx.89
地址 : 中国 北京
运营商 : 联通
数据二 : 北京市 | 联通
数据三 : 中国北京北京 | 联通
URL : http://www.cip.cc/111.xxx.xxx.89
可以看到该请求方式获取到的信息非常详细,包括出口ip、包括运营商、地址等信息
如果仅仅获取IP,可以使用(不过尝试的时候,会出现卡顿)
curl ip.cip.cc
可以登录cip.cc网站查看

方式二
curl ifconfig.io
该请求会直接将出口ip返回
111.xxx.xxx.89
可以登录ifconfig.io查看一些常用的curl命令

方式三
借助类似aws的服务
curl http://checkip.amazonaws.com
该请求也是直接将出口ip返回
111.xxx.xxx.89
java代码
@Slf4j
public class IpUtils {
public static final String AWS_COM_URL = "http://checkip.amazonaws.com";
// 该方式极有可能出现卡顿,不建议使用
public static final String CIP_CC_URL = "http://ip.cip.cc";
public static final String IFCONFIG_IO_URL = "http://ifconfig.io/ip";
/**
* 直接获取本机的ip
*/
public static void getLocalIp() {
try {
InetAddress localHost = InetAddress.getLocalHost();
String localIp = localHost.getHostAddress();
log.info("localIp:{}", localIp);
} catch (Exception e) {
log.error("getLocalIp error, msg:{}", e.getMessage(), e);
}
}
/**
* 通过访问一些外部服务,获取到本机的出口Ip
* @throws MalformedURLException
*/
public static void getExternalIp(String urlStr) throws MalformedURLException {
if (StringUtils.isEmpty(urlStr)) {
urlStr = AWS_COM_URL;
}
URL url = new URL(urlStr);
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()))) {
String ip = bufferedReader.readLine();
log.info("externalIp:{}", ip);
} catch (IOException e) {
log.error("get ExternalIp error, msg:{}", e.getMessage(), e);
}
}
public static void main(String[] args) throws MalformedURLException {
IpUtils.getLocalIp();
IpUtils.getExternalIp(IpUtils.AWS_COM_URL);
IpUtils.getExternalIp(IpUtils.CIP_CC_URL);
IpUtils.getExternalIp(IpUtils.IFCONFIG_IO_URL);
}
}
网友评论