Android获取用户ip地址

public class NetManager {

    /**
     * 获取用户IP地址
* 注意:需要在androidManifest.xml中声明下面三个权限才能正常使用该方法,否则会空指针异常 * * * */
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,实际问题,android,tcp/ip,网络协议)