获取当前IP地址

获取当前IP地址:

package com.international.wtw.lottery.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class NetWorkIPUtils {

    public static String getIPAddress(Context context) {
        String strIPAddress = "";
        NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null) {
            boolean available = info.isAvailable();//判断网络是否可用
            boolean connected = info.isConnected();//判断网络是否连接
            if (available && connected) {
                if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//手机网络
                    try {
                        for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                            NetworkInterface inter = en.nextElement();
                            for (Enumeration enumIpAddress = inter.getInetAddresses(); enumIpAddress.hasMoreElements(); ) {
                                InetAddress inetAddress = enumIpAddress.nextElement();
                                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                    strIPAddress = inetAddress.getHostAddress();
                                }
                            }
                        }
                    } catch (SocketException e) {
                        e.printStackTrace();
                    }
                } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//WIFI网络
                    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    strIPAddress = int2ip(wifiInfo.getIpAddress());
                }
            } else {
                LogUtil.e("info网络不可用或未连接");
            }
        } else {
            LogUtil.e("info信息为空");
        }
        return strIPAddress;
    }

    /**
     * 将ip的整数形式转换成ip形式
     *
     * @param ipInt
     * @return
     */
    private static String int2ip(int ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }

}

你可能感兴趣的:(获取当前IP地址)