获取公网ip的几种方式

以下四种方式都可以查询到公网的出口ip

  • https://ifconfig.me/ip
  • https://myip.ipip.net/s
  • https://ip.useragentinfo.com/json
  • http://ip-api.com/json

以下是获取ip的java代码:

	static private String getIpFromMyIp() {
        String ipRet = OkHttpRequestUtil.requestGet("https://myip.ipip.net/s");
        if (StringUtils.isBlank(ipRet)) {
            return "";
        }
        return StringUtils.trim(ipRet);
    }

    static private String getIpFromUserAgent() {
        String ipRet = OkHttpRequestUtil.requestGet("https://ip.useragentinfo.com/json");
        if (StringUtils.isBlank(ipRet)) {
            return "";
        }
        try {
            JSONObject jsonObject = JSON.parseObject(ipRet);
            return StringUtils.trimToEmpty(jsonObject.getString("ip"));
        } catch (Exception e) {
            logger.error("getIpFromUserAgent error", e);
        }
        return "";
    }

    // http://ip-api.com/json
    static private String getFromIpApi() {
        String ipRet = OkHttpRequestUtil.requestGet("http://ip-api.com/json");
        if (StringUtils.isBlank(ipRet)) {
            return "";
        }
        try {
            JSONObject jsonObject = JSON.parseObject(ipRet);
            return StringUtils.trimToEmpty(jsonObject.getString("query"));
        } catch (Exception e) {
            logger.error("getFromIpApi error", e);
        }
        return "";
    }

附ok http的代码:

			<dependency>
                <groupId>com.squareup.okhttp3</groupId>
                <artifactId>okhttp</artifactId>
                <version>3.14.9</version>
            </dependency>

public class OkHttpRequestUtil {
    private static final Logger logger = LoggerFactory.getLogger(OkHttpRequestUtil.class);
    public static OkHttpClient okHttpClient;

    static {
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequests(500);
        dispatcher.setMaxRequestsPerHost(500);
        okHttpClient = (new OkHttpClient.Builder())
                .connectTimeout(Duration.ofSeconds(5))
                .callTimeout(Duration.ofSeconds(5))
                .readTimeout(Duration.ofSeconds(5))
                .writeTimeout(Duration.ofSeconds(5))
                .connectionPool(new ConnectionPool(100, 120L, TimeUnit.MINUTES))
                .dispatcher(dispatcher).build();
    }

    public static String requestGet(String url) {
        return request("get", url, null);
    }

    private static String request(String method, String urlPath, String jsonString) {
        Request.Builder builder = (new Request.Builder()).url(urlPath);
        if ("post".equals(method)) {
            RequestBody requestBody;
            if (jsonString != null) {
                requestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), jsonString);
            } else {
                requestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), new byte[0]);
            }

            builder.post(requestBody);
        }

        Request request = builder
                .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 10; Redmi K30 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36")
                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7")
                .build();

        try {
            Response response = okHttpClient.newCall(request).execute();
            if (response != null && response.body() != null) {
                return response.body().string();
            }
        } catch (Exception e) {
            logger.error("request error", e);
        }

        return "";
    }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

namedlock

您的鼓励是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值