Linux服务器如何获取出口ip

本周因为工作需要,需要获取服务器对应的出口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网站查看

截屏2021-09-04 下午4.34.07

方式二

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);
    }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

51iwowo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值