자바, 이 컴퓨터 내 네트워크 ip, 외부 네트워크 ip 가 져 오기

1716 단어 종합 하 다
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 "  ";
        }
    }

}

좋은 웹페이지 즐겨찾기