Search code examples
c++macosnetwork-programmingwififirebreath

How to Scan For Wifi Access Points in C++ on Mac OS X


I need to scan for and gather information about local Wifi access points in Mac OS X Linux in C++. This perhaps uses Wlan or something akin to WlanScan. I have similar code working in Windows that cannot possibly be translated.

This code is being built in a FireBreath development project.

Do you have an example or suggestion for scanning Wifi access points in C++ on Mac?


Solution

  • You can't do this in plain C++, but you can use Objective-C++ (you source file just need to have .mm extension and you can use Objective-C right in your C++ code). Take a look at CoreWLAN framework. You should write something like this:

    #import <CoreWLAN/CoreWLAN.h>
    
    struct AccessPoint
    {
        string ssid;
        string bssid;
        int rssi;
    };
    
    vector<AccessPoint> ScanAir(const string& interfaceName)
    {
        NSString* ifName = [NSString stringWithUTF8String:interfaceName.c_str()];
        CWInterface* interface = [CWInterface interfaceWithName:ifName];
    
        NSError* error = nil;
        NSArray* scanResult = [[interface scanForNetworksWithSSID:nil error:&error] allObjects];
        if (error)
        {
            NSLog(@"%@ (%ld)", [error localizedDescription], [error code]);
        }
    
        vector<AccessPoint> result;
        for (CWNetwork* network in scanResult)
        {
            AccessPoint ap;
            ap.ssid  = string([[network ssid] UTF8String]);
            ap.bssid = string([[network bssid] UTF8String]);
            ap.rssi = [network rssiValue];
            result.push_back(ap);
        }
    
        return result;
    }
    

    I didn't test this code, but I use similar code in my project, so it should work. Note also that I'm using ARC here. If you'll get some errors - feel free to ask in comments.
    There is also example in apple documentation, but it is somewhat outdated (it is for OS X 10.6). There were some changes in OS X 10.7.

    Note that CoreWLAN framework requires OS X 10.6 or greater.