wifi mobile 獲取 IP MAC等信息

wifi 狀態(tài)下懈叹,只能獲取到路由分配的內(nèi)部地址192.168.xxx.xxx 無法獲取真實(shí)服務(wù)器地址,(可以依賴對(duì)外部網(wǎng)絡(luò)請(qǐng)求返回,來獲取自己的真實(shí)服務(wù)器地址)



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 計(jì)算網(wǎng)絡(luò)數(shù)據(jù)統(tǒng)計(jì)
 */
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 數(shù)據(jù)類型  0:移動(dòng)網(wǎng)絡(luò)   1:wifi      其他:全部數(shù)據(jù)
     * @param dateType 日期類型  0:本日      1:本月
     * @return 接受與發(fā)送的總和
     */
    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);//整機(jī)
                    //        networkStatsManager.querySummary();//當(dāng)前應(yīng)用
                    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;
    }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子特漩,更是在濱河造成了極大的恐慌,老刑警劉巖骨杂,帶你破解...
    沈念sama閱讀 207,113評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件涂身,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡搓蚪,警方通過查閱死者的電腦和手機(jī)蛤售,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,644評(píng)論 2 381
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來妒潭,“玉大人悴能,你說我怎么就攤上這事■ㄔ郑” “怎么了漠酿?”我有些...
    開封第一講書人閱讀 153,340評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)谎亩。 經(jīng)常有香客問我炒嘲,道長(zhǎng),這世上最難降的妖魔是什么匈庭? 我笑而不...
    開封第一講書人閱讀 55,449評(píng)論 1 279
  • 正文 為了忘掉前任夫凸,我火速辦了婚禮,結(jié)果婚禮上阱持,老公的妹妹穿的比我還像新娘夭拌。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,445評(píng)論 5 374
  • 文/花漫 我一把揭開白布啼止。 她就那樣靜靜地躺著道逗,像睡著了一般。 火紅的嫁衣襯著肌膚如雪献烦。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,166評(píng)論 1 284
  • 那天卖词,我揣著相機(jī)與錄音巩那,去河邊找鬼。 笑死此蜈,一個(gè)胖子當(dāng)著我的面吹牛即横,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播裆赵,決...
    沈念sama閱讀 38,442評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼东囚,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了战授?” 一聲冷哼從身側(cè)響起页藻,我...
    開封第一講書人閱讀 37,105評(píng)論 0 261
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎植兰,沒想到半個(gè)月后份帐,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,601評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡楣导,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,066評(píng)論 2 325
  • 正文 我和宋清朗相戀三年废境,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片筒繁。...
    茶點(diǎn)故事閱讀 38,161評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡噩凹,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出毡咏,到底是詐尸還是另有隱情驮宴,我是刑警寧澤,帶...
    沈念sama閱讀 33,792評(píng)論 4 323
  • 正文 年R本政府宣布血当,位于F島的核電站幻赚,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏臊旭。R本人自食惡果不足惜落恼,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,351評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望离熏。 院中可真熱鬧佳谦,春花似錦、人聲如沸滋戳。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,352評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至咪笑,卻和暖如春可帽,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背窗怒。 一陣腳步聲響...
    開封第一講書人閱讀 31,584評(píng)論 1 261
  • 我被黑心中介騙來泰國(guó)打工映跟, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人扬虚。 一個(gè)月前我還...
    沈念sama閱讀 45,618評(píng)論 2 355
  • 正文 我出身青樓努隙,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親辜昵。 傳聞我的和親對(duì)象是個(gè)殘疾皇子荸镊,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,916評(píng)論 2 344

推薦閱讀更多精彩內(nèi)容