在進行Android應用開發過程中,有時候會遇到獲取當前Android設備所使用的網絡IP地址的場景,有時候需要本地的網絡IP地址,即局域網地址,更多的時候是需要當前網絡的真實的對外IP地址,即真實的網絡地址,如大數據分析時往往需要Android設備上傳本地的外網地址。本文對各種IP地址的獲取進行了總結。
首先用大家比較熟悉的電腦端局域網地址和外網地址的獲取方式對比一下:(1)、電腦端局域網地址獲取方式,可以通過在終端命令行輸入ipconfig進行查看,如下圖IPv地址標識的就是本機的局域網地址:
(2)、電腦端外網地址的獲取方式,可以通過在瀏覽器裏面查詢,如在百度頁面搜索“IP地址查詢”查看本地外網地址,如下圖是筆者本機的外網地址:
1.本地IP地址有兩種情況:一是wifi下,二是移動網絡下
1.1wifi下獲取本地局域網IP地址
// wifi下獲取本地網絡IP地址(局域網地址)
public static String getLocalIPAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null) {
@SuppressLint("MissingPermission") WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());
return ipAddress;
}
return "";
}
1.2.移動網絡獲取網絡IP地址
// 獲取有限網IP
public static String getHostIp() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()
&& inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (Exception ex) {
}
return "0.0.0.0";
}
2.獲取外網地址(非移動網絡
獲取Android設備的外網地址,即當前Wifi網絡真正的網絡地址,也即是網絡運營商分配給用戶的IP地址。
獲取外網地址的原理:通過訪問外網網站,從網站返回的數據中解析本地的IP地址。PS:在本地是無法獲取到外網的IP地址的,需要藉助服務器。
/**
* 獲取外網ip地址(非本地局域網地址)的方法
*/
public static String getOutNetIP() {
String ipAddress = "";
try {
String address = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip";
URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setUseCaches(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("user-agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.7 Safari/537.36"); //設置瀏覽器ua 保證不出現503
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = connection.getInputStream();
// 將流轉化爲字符串
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String tmpString;
StringBuilder retJSON = new StringBuilder();
while ((tmpString = reader.readLine()) != null) {
retJSON.append(tmpString + "\n");
}
JSONObject jsonObject = new JSONObject(retJSON.toString());
String code = jsonObject.getString("code");
Log.e(TAG, "提示:" +retJSON.toString());
if (code.equals("0")) {
JSONObject data = jsonObject.getJSONObject("data");
ipAddress = data.getString("ip")/* + "(" + data.getString("country")
+ data.getString("area") + "區"
+ data.getString("region") + data.getString("city")
+ data.getString("isp") + ")"*/;
Log.e(TAG, "您的IP地址是:" + ipAddress);
} else {
Log.e(TAG, "IP接口異常,無法獲取IP地址!");
}
} else {
Log.e(TAG, "網絡連接異常,無法獲取IP地址!");
}
} catch (Exception e) {
Log.e(TAG, "獲取IP地址時出現異常,異常信息是:" + e.toString());
}
return ipAddress;
}
3.根據網絡類型集成方法
@SuppressLint("MissingPermission")
public static String getIpAddress(Context context) {
if (context == null) {
return "";
}
ConnectivityManager conManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
NetworkInfo info = conManager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
// 3/4g網絡
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
return getHostIp();
} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
// return getLocalIPAddress(context); // 局域網地址
return getOutNetIP(); // 外網地址
} else if (info.getType() == ConnectivityManager.TYPE_ETHERNET) {
// 以太網有限網絡
return getHostIp();
}
}
} catch (Exception e) {
return "";
}
return "";
}