wifi mobile 獲取 IP MAC等信息

wifi 狀態下,只能獲取到路由分配的內部地址192.168.xxx.xxx 無法獲取真實服務器地址,(可以依賴對外部網絡請求返回,來獲取自己的真實服務器地址)



import android.app.Application;
import android.app.usage.NetworkStats;
import android.app.usage.NetworkStatsManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.RemoteException;

import com.kalerm.android.pbjx.app.iot.bean.NetworkType;
import com.kalerm.android.pbjx.app.ui.online.bean.CommonBean;

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


/**
 * 2023/11/6
 * ..╭︿︿︿╮
 * {/ .  . /}
 * .( (oo) )    create by cps
 * .︶︶︶
 * for 計算網絡數據統計
 */
public class NetworkByteUtil {
    private Context context;
    private static NetworkByteUtil mInstance;

    private NetworkByteUtil(Application application) {
        context = application;
    }

    public static NetworkByteUtil getInstance(Application application) {
        if (mInstance == null) {
            mInstance = new NetworkByteUtil(application);
        }
        return mInstance;
    }


    /**
     * @param DataType 數據類型  0:移動網絡   1:wifi      其他:全部數據
     * @param dateType 日期類型  0:本日      1:本月
     * @return 接受與發送的總和
     */
    public long getDataByteByType(int DataType, int dateType) {
        NetworkStatsManager networkStatsManager = (NetworkStatsManager)
                context.getSystemService(Context.NETWORK_STATS_SERVICE);
        long endTime = System.currentTimeMillis();
        long startLongTime;
        if (dateType == 0) {
            startLongTime = getTodayLongTime();
        } else {
            startLongTime = getCMonthLongTime();

        }
        if (startLongTime < 1) {
            return -1;
        }
        CommonBean result = new CommonBean();
        try {
            switch (DataType) {
                case 0:
                    NetworkStats.Bucket bucketOnlyMobile = networkStatsManager
                            .querySummaryForDevice(ConnectivityManager.TYPE_MOBILE, null,
                                    startLongTime, endTime);//整機
                    //        networkStatsManager.querySummary();//當前應用
                    result.setData1(bucketOnlyMobile.getRxBytes());
                    result.setData2(bucketOnlyMobile.getTxBytes());
                    break;
                case 1:
                    NetworkStats.Bucket bucketOnlyWifi = networkStatsManager
                            .querySummaryForDevice(ConnectivityManager.TYPE_WIFI, null,
                                    startLongTime, endTime);
                    result.setData1(bucketOnlyWifi.getRxBytes());
                    result.setData2(bucketOnlyWifi.getTxBytes());
                    break;
                default:
                    NetworkStats.Bucket bucketMobile = networkStatsManager
                            .querySummaryForDevice(ConnectivityManager.TYPE_MOBILE, null,
                                    startLongTime, endTime);
                    NetworkStats.Bucket bucketWifi = networkStatsManager
                            .querySummaryForDevice(ConnectivityManager.TYPE_WIFI, null,
                                    startLongTime, endTime);
                    long rxBytes = bucketMobile.getRxBytes() + bucketWifi.getRxBytes();
                    long txBytes = bucketMobile.getTxBytes() + bucketWifi.getTxBytes();
                    result.setData1(rxBytes);
                    result.setData2(txBytes);
                    break;


            }


        } catch (RemoteException e) {
            e.printStackTrace();
            return -1;
        }
        LogUtil.d("query bytes is received:" + result.getData1() + ".Sent :" + result.getData2());
        return result.getData1() + result.getData2();
    }

    private long getTodayLongTime() {
        String dateStr = TimeUtil.getDate();//"yyyy/MM/dd"
        long longTimeByTag = TimeUtil.getLongTimeByTag(dateStr, "yyyy/MM/dd");
        LogUtil.d("start query net—data day-time is :" + longTimeByTag);
        return longTimeByTag;
    }

    private long getCMonthLongTime() {
        String dateStr = TimeUtil.formatDateByTimeL(System.currentTimeMillis(), "yyyy/MM") + "/01";//"yyyy/MM/dd"
        long longTimeByTag = TimeUtil.getLongTimeByTag(dateStr, "yyyy/MM/dd");
        LogUtil.d("start query net—data month-time is :" + longTimeByTag);
        return longTimeByTag;
    }


    public String getLocalIpAddress() {
        String resultIp = "";
        String netWorkType = AndroidUtil.getNetWorkType(context);
        if (netWorkType.equals("WIFI")) {
            try {
                resultIp = getWifiIpAddress();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (netWorkType.equals("MOBILE")) {
            try {
                resultIp = getMobileIpAddress();
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }
        return resultIp;
    }


    private String getWifiIpAddress() throws Exception {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String beDispatchedIpStr = String.format(Locale.getDefault(), "%d.%d.%d.%d", (ipAddress & 0xff)
                , (ipAddress >> 8 & 0xff)
                , (ipAddress >> 16 & 0xff)
                , (ipAddress >> 24 & 0xff));
        LogUtil.d("wifi dispatched Ip IS :" + beDispatchedIpStr);
        return beDispatchedIpStr;
    }

    /**
     * found ip is:fe80::6065:1ff:fe95:3626%dummy0
     * found ip is:::1
     * found ip is:127.0.0.1
     * found ip is:fe80::d87e:bde3:e5b3:a734%rmnet_data0
     * found ip is:fe80::4fe0:305f:9deb:3f77%rmnet_data2
     * found ip is:2409:8920:4c51:44e0:4fe0:305f:9deb:3f77
     * found ip is:10.62.147.249
     * found ip is:fe80::9287:ab5:1161:7ec4%rmnet_data1
     * found ip is:2409:8121:4d70:9e2a:9287:ab5:1161:7ec4
     * <p>
     * <p>
     */
    private String getMobileIpAddress() throws SocketException {
        String ipv4String = "";

        String ipv6String = "";
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            if (!networkInterface.isUp()) {
                continue;
            }

            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
//                if (!inetAddress.isLoopbackAddress()&&inetAddress.isSiteLocalAddress()){
                // 此方式也可獲得IPV4 ip值
//                }
                LogUtil.d("found ip is: " + inetAddress.toString());
                if (inetAddress instanceof Inet4Address) {
                    ipv4String = inetAddress.getHostAddress();
                } else if (inetAddress instanceof Inet6Address) {
                    ipv6String = inetAddress.getHostAddress();
                }
            }


        }
        LogUtil.d("ipv4: " + ipv4String + "    ipv6 : " + ipv6String);
        return ipv4String;
    }

    /**
     * : mac address is : 04:86:80:4A:DF:EE
     *
     * @return
     * @throws SocketException
     */
    public String getMacAddress() throws SocketException {
        String macAddressStr = "";
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            if (networkInterface.getName().equalsIgnoreCase("wlan0")) {
                byte[] macBytes = networkInterface.getHardwareAddress();
                if (macBytes != null && macBytes.length > 0) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (byte b : macBytes) {
                        stringBuilder.append(String.format("%02X:", b));
                    }
                    macAddressStr = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
                    break;
                }
            }
        }
        LogUtil.d("mac address is : " + macAddressStr);
        return macAddressStr;
    }

}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容