1. 程式人生 > >JAVA 獲取當前 內網 和 外網 的IP 地址

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;
  }
}