java 获取本机内网ip、外网ip

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;

import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;


/**
 * ip
 *
 * @author lijinzhou
 * @since 2019/11/12  17:00
 */
public class IpUtil {


    /**
     * 获取当前服务器的IP地址(内网)
     *
     * @author lijinzhou
     * @since 2019/11/12 16:39
     */
    public static String getHostAddress() {
        try {
            InetAddress address = InetAddress.getLocalHost();
            return address.getHostAddress();
        } catch (Exception e) {
            return "未知";
        }
    }

    /**
     * 获取本机外网ip
     *
     * @author lijinzhou
     * @since 2019/11/12 17:23
     */
    public static String getPublicIp() {
        try {
            String ip = "http://pv.sohu.com/cityjson?ie=utf-8";
            URL url = new URL(ip);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String read;
            while ((read = in.readLine()) != null) {
                stringBuilder.append(read);
            }
            //可打印stringBuilder再解析得到的信息
            String string = StringUtils.split(stringBuilder.toString(), "=")[1];
            JSONObject jsonObject = JSONUtil.parseObj(string);
            return jsonObject.get("cip").toString();
        } catch (Exception e) {
            return "未知";
        }
    }

}

你可能感兴趣的:(综合)