Android获取用户ip地址
Posted wodongx123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android获取用户ip地址相关的知识,希望对你有一定的参考价值。
public class NetManager
/**
* 获取用户IP地址<br/>
* 注意:需要在androidManifest.xml中声明下面三个权限才能正常使用该方法,否则会空指针异常
* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
* <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
* <uses-permission android:name="android.permission.INTERNET"/>
*/
public static String getIpAddress(Context context)
if (context == null)
return "";
ConnectivityManager conMann = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mobileNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mobileNetworkInfo.isConnected())
return getLocalIpAddress();
else if (wifiNetworkInfo.isConnected())
return getWifiAddress(context);
return "";
private static String getLocalIpAddress()
try
ArrayList<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface ni : nilist)
ArrayList<InetAddress> ialist = Collections.list(ni.getInetAddresses());
for (InetAddress address : ialist)
if (!address.isLoopbackAddress() && address instanceof Inet4Address)
return address.getHostAddress();
catch (SocketException e)
e.printStackTrace();
return "";
private static String getWifiAddress(Context context)
if (context == null)
return "";
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
return intToIp(ipAddress);
private static String intToIp(int ipInt)
String s = (ipInt & 0xFF) + "." +
((ipInt >> 8) & 0xFF) + "." +
((ipInt >> 16) & 0xFF) + "." +
((ipInt >> 24) & 0xFF);
return s;
经过实测,并不能真的获取到网络上实际的外网IP地址,只能拿到他下面的内网IP地址,凑合着用吧
参考来源:https://blog.csdn.net/sinat_16458039/article/details/50260589
以上是关于Android获取用户ip地址的主要内容,如果未能解决你的问题,请参考以下文章