简体   繁体   English

使用 flutter 获取我的手机连接到的 wifi 路由器的 mac 地址

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

I have been trying to get the the mac address of my wifi router that my device is connected to.我一直在尝试获取我的设备连接到的 wifi 路由器的 mac 地址。 I am using Flutter.我正在使用 Flutter。

I have come across few plugins like get_ip , wifi_info_plugin and also flutter_ip .我遇到过一些插件,比如get_ipwifi_info_pluginflutter_ip But either it shows unknown, doesn't support android, doesn't support ios or just shows nothing at all.但它要么显示未知,要么不支持 android,要么不支持 ios,要么什么都不显示。

What I am trying to do is to make my app run only when connected to one specific wifi router .我想要做的是让我的应用程序仅连接到一个特定的 wifi 路由器时运行。 So basically some features of the app will be disabled when connected to a different wifi router other than mine.所以基本上,当连接到我以外的其他 wifi 路由器时,应用程序的某些功能将被禁用。

Please suggest any other plugin or any work around.请建议任何其他插件或任何解决方法。

You can use you SystemConfiguration.CaptiveNetwork framework to copy your current.network info from the supported interfaces.您可以使用SystemConfiguration.CaptiveNetwork框架从支持的接口复制您的 current.network 信息。 Note that you would need to allow access your device's location and enable Hotspot Configuration and Access WiFi Information in your app capabilities:请注意,您需要允许访问您设备的位置并在您的应用功能中启用热点配置和访问 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
        }
    }
}

Thanks guys, I was searching for this answer too.谢谢大家,我也在找这个答案。

Refer the code mentioned below.请参考下面提到的代码。 And enable permission of Location and enable Location too.并启用位置权限并启用位置。

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),
        ),
      ),
    );
  }
}




It seems like the wifi_info_plugin is your best bet. wifi_info_plugin似乎是您最好的选择。 Follow the documentation, and try to get the AP MAC like so:按照文档,并尝试像这样获取 AP MAC:

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

Make sure that AP_MAC != "missing" , and wrap in a try/catch in case it throws a PlatformException .确保AP_MAC != "missing" ,并包裹在 try/catch 中以防它抛出PlatformException This may not work for iOS devices.这可能不适用于 iOS 设备。

I had the same problem.我有同样的问题。 I end up using location package.我最终使用位置 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