在进行Android应用开发过程中,有时候会遇到获取当前Android设备所使用的网络IP地址的场景,有时候需要本地的网络IP地址,即局域网地址,更多的时候是需要当前网络的真实的对外IP地址,即真实的网络地址,如大数据分析时往往需要Android设备上传本地的外网地址。本文对各种IP地址的获取进行了总结。
首先用大家比较熟悉的电脑端局域网地址和外网地址的获取方式对比一下:(1)、电脑端局域网地址获取方式,可以通过在终端命令行输入ipconfig进行查看,如下图IPv地址标识的就是本机的局域网地址:
(2)、电脑端外网地址的获取方式,可以通过在浏览器里面查询,如在百度页面搜索“IP地址查询”查看本地外网地址,如下图是笔者本机的外网地址:
本地IP地址有两种情况:一是wifi下,二是移动网络下
wifi下获取本地局域网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 "";
}
移动网络获取网络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";
}
获取外网地址非移动网络
获取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;
}
根据网络类型集成方法
@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 "";
}
下面在为大家提供两个获取手机IP地址的实例源码
获取内网IP地址
/**
* 获取ip地址
* @return
*/
public static String getHostIP() {
String hostIp = null;
try {
Enumeration nis = NetworkInterface.getNetworkInterfaces();
InetAddress ia = null;
while (nis.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) nis.nextElement();
Enumeration<InetAddress> ias = ni.getInetAddresses();
while (ias.hasMoreElements()) {
ia = ias.nextElement();
if (ia instanceof Inet6Address) {
continue;// skip ipv6
}
String ip = ia.getHostAddress();
if (!"127.0.0.1".equals(ip)) {
hostIp = ia.getHostAddress();
break;
}
}
}
} catch (SocketException e) {
Log.i("yao", "SocketException");
e.printStackTrace();
}
return hostIp;
}
获取外网IP地址
/**
* 获取IP地址
* @return
*/
public static String GetNetIp() {
URL infoUrl = null;
InputStream inStream = null;
String line = "";
try {
infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
URLConnection connection = infoUrl.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
inStream = httpConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
// 从反馈的结果中提取出IP地址
int start = strber.indexOf("{");
int end = strber.indexOf("}");
String json = strber.substring(start, end + 1);
if (json != null) {
try {
JSONObject jsonObject = new JSONObject(json);
line = jsonObject.optString("cip");
} catch (JSONException e) {
e.printStackTrace();
}
}
return line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
本文主要讲解了Android获取手机内网IP地址与外网IP地址的详细方法与源码实例,更多关于Android开发知识与技巧请查看下面的相关链接
您可能感兴趣的文章:Android获得设备状态信息、Mac地址、IP地址的方法Android中使用adb命令通过IP地址连接手机Android实现IP地址输入框的方法示例代码Android开发实现在Wifi下获取本地IP地址的方法Android 判断ip地址合法实现代码Android 获取IP地址的实现方法android 获取本机的IP地址和mac物理地址的实现方法android实现获取有线和无线Ip地址的方法Android手机获取IP地址的两种方法Android开发准确获取手机IP地址的两种方式