簡體   English   中英

使用 flutter 獲取我的手機連接到的 wifi 路由器的 mac 地址

[英]Get mac address of the wifi router my phone is connected to, using flutter

我一直在嘗試獲取我的設備連接到的 wifi 路由器的 mac 地址。 我正在使用 Flutter。

我遇到過一些插件,比如get_ipwifi_info_pluginflutter_ip 但它要么顯示未知,要么不支持 android,要么不支持 ios,要么什么都不顯示。

我想要做的是讓我的應用程序僅連接到一個特定的 wifi 路由器時運行。 所以基本上,當連接到我以外的其他 wifi 路由器時,應用程序的某些功能將被禁用。

請建議任何其他插件或任何解決方法。

您可以使用SystemConfiguration.CaptiveNetwork框架從支持的接口復制您的 current.network 信息。 請注意,您需要允許訪問您設備的位置並在您的應用功能中啟用熱點配置和訪問 WiFi 信息:

import UIKit
import CoreLocation
import SystemConfiguration.CaptiveNetwork
import NetworkExtension

class ViewController: UIViewController, CLLocationManagerDelegate {
    let locationManager = CLLocationManager()
    var ssid = ""
    var bssid = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if #available(iOS 14.0, *) {
            fetchNetworkInfo()
        } else {
            fetchBSSIDInfo()
        }
        locationManager.stopUpdatingLocation()
    }
    @available(iOS, introduced: 4.1.0, deprecated: 14.0)
    func fetchBSSIDInfo()  {
        if let interfaces = CNCopySupportedInterfaces() as? [CFString]  {
            for interface in interfaces {
                if let currentNetworkInfo = CNCopyCurrentNetworkInfo(interface) as? [CFString: Any]  {
                    ssid = currentNetworkInfo[kCNNetworkInfoKeySSID] as? String ?? ""
                    print("ssid:", ssid)
                    bssid = currentNetworkInfo[kCNNetworkInfoKeyBSSID] as? String ?? ""
                    print("bssid:", bssid)
                    break
                }
            }
        }
    }
    @available(iOS 14.0, *)
    func fetchNetworkInfo() {
        NEHotspotNetwork.fetchCurrent { network in
            guard let network = network else { return }
            
            print("The SSID for the Wi-Fi network.")
            print("ssid:", network.ssid, "\n")
            self.ssid = network.ssid

            print("The BSSID for the Wi-Fi network.")
            print("bssid:", network.bssid, "\n")
            self.bssid = network.bssid
            
            print("The recent signal strength for the Wi-Fi network.")
            print("signalStrength:", network.signalStrength, "\n")
            
            print("Indicates whether the network is secure")
            print("isSecure:", network.isSecure, "\n")
            
            print("Indicates whether the network was joined automatically or was joined explicitly by the user.")
            print("didAutoJoin:", network.didAutoJoin, "\n")
            
            print("Indicates whether the network was just joined.")
            print("didJustJoin:", network.didJustJoin, "\n")
            
            print("Indicates whether the calling Hotspot Helper is the chosen helper for this network.")
            print("isChosenHelper:", network.isChosenHelper, "\n")
        }
    }

    @available(iOS, introduced: 13.2.0, deprecated: 14.0)
    func locationManager(_ manager: CLLocationManager,
                         didChangeAuthorization status: CLAuthorizationStatus) {
        didChangeAuthorization(status: status)
    }
    @available(iOS 14.0, *)
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        didChangeAuthorization(status: manager.authorizationStatus)
    }
    func didChangeAuthorization(status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined:
            print("The user has not chosen whether the app can use location services.\n")
        case .restricted:
            print("The app is not authorized to use location services.\n")
        case .denied:
            print("The user denied the use of location services for the app or they are disabled globally in Settings.\n")
        case .authorizedAlways:
            print("The user authorized the app to start location services at any time.\n")
        case .authorizedWhenInUse:
            print("The user authorized the app to start location services while it is in use.\n")
        @unknown default: break
        }
        switch status {
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
        case .restricted, .denied:
            let alert = UIAlertController(title: "Allow Location Access",
                                          message: "Please turn on Location Services",
                                          preferredStyle: .alert)
            alert.addAction(.init(title: "Settings",
                                  style: .default) { _ in
                let url = URL(string: UIApplication.openSettingsURLString)!
                if UIApplication.shared.canOpenURL(url) {
                    UIApplication.shared.open(url) { success in
                        print("Settings opened: \(success)")
                    }
                }
            })
            alert.addAction(.init(title: "Ok", style: .default))
            DispatchQueue.main.async {
                self.present(alert, animated: true)
            }
        case .authorizedWhenInUse, .authorizedAlways:
            locationManager.startUpdatingLocation()
        @unknown default: break
        }
    }
}

謝謝大家,我也在找這個答案。

請參考下面提到的代碼。 並啟用位置權限並啟用位置。

class _MyAppState extends State<MyApp> {
  WifiInfoWrapper _wifiObject;

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    WifiInfoWrapper wifiObject;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      wifiObject = await WifiInfoPlugin.wifiDetails;
    } on PlatformException {}
    if (!mounted) return;

    setState(() {
      _wifiObject = wifiObject;
    });
  }

  @override
  Widget build(BuildContext context) {
    String macAddress = _wifiObject != null ? _wifiObject.bssId.toString() : "mac";
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text('Mac of AP - ' + macAddress),
        ),
      ),
    );
  }
}




wifi_info_plugin似乎是您最好的選擇。 按照文檔,並嘗試像這樣獲取 AP MAC:

wifiObject = await  WifiInfoPlugin.wifiDetails;
AP_MAC = wifiObject.bssId.toString();

確保AP_MAC != "missing" ,並包裹在 try/catch 中以防它拋出PlatformException 這可能不適用於 iOS 設備。

我有同樣的問題。 我最終使用位置 package。

 location: ^3.0.2


bool _serviceEnabled;
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
    _serviceEnabled = await location.requestService();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM