JAVA 获取当前 内网 和 外网 的IP 地址

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

public class UserIP {

/**

  • @param args
  • @throws Exception
    *@author liuwl
    */
    public static void main(String[] args) throws Exception {
    System.out.println(“本机的外网IP是:”+UserIP.getWebIP(“http://www.ip138.com/ip2city.asp”));
    System.out.println(“本机的内网IP是:”+UserIP.getLocalIP());
    }

/**

  • 获取外网地址
  • @param strUrl
  • @return
    */
    public static String getWebIP(String strUrl) {
    try {
    //连接网页
    URL url = new URL(strUrl);
    BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
    String s = “”;
    StringBuffer sb = new StringBuffer("");
    String webContent = “”;
    //读取网页信息
    while ((s = br.readLine()) != null) {
    sb.append(s + “\r\n”);
    }
    br.close();
    //网页信息
    webContent = sb.toString();
    int start = webContent.indexOf("[")+1;
    int end = webContent.indexOf("]");
    //获取网页中 当前 的 外网IP
    webContent = webContent.substring(start,end);
    return webContent;

} catch (Exception e) {
e.printStackTrace();
return “error open url:” + strUrl;
}
}

public static String getLocalIP() throws Exception{
String localIP = “”;
InetAddress addr = (InetAddress) InetAddress.getLocalHost();
//获取本机IP
localIP = addr.getHostAddress().toString();
return localIP;
}
}
外部链接:https://blog.csdn.net/LOVELONG8808/article/details/40654325

发布了13 篇原创文章 · 获赞 3 · 访问量 2058

猜你喜欢

转载自blog.csdn.net/qq_33337186/article/details/98061013
今日推荐