Can objective-C log into a wifi network programmat

2020-03-30 16:34发布

问题:

Imagine that on your hard drive you had a local collection of public wi-fi names and passwords such as those that are found in coffeeshops. And you enter a coffeeshop where you have never been before, and an OSX app matches an available wifi network as one on the list and signs you in. Is this possible with objective c?

回答1:

You can use CoreWLAN to scan, connect, disconnect and etc. to WiFi networks. Here is a short and simplified example how to scan for networks and connect to a network:

#import <CoreWLAN/CoreWLAN.h>

CWInterface *cwInterface = [[CWInterface alloc] initWithInterfaceName:@"en1"]; // specify here the WiFi interface
NSError *err = nil;

// get all networks
NSSet *networksSet = [cwInterface scanForNetworksWithName:nil error:&err];
NSArray *allNetworks = [networksSet allObjects];

CWNetwork *selectedNetwork;

// check if one of the scanned networks SSIDs matches network with SSID "network_name"
for (CWNetwork *network in allNetworks) {

    // perhaps you will have another for here, looping over NSDictionary with network name as key and password as value
    if ([network.ssid isEqualToString:@"network_name"]) {
        selectedNetwork = network;
    }
}

// finally connect to the selected network
[cwInterface associateToNetwork:selectedNetwork password:@"network_password" error:&err];

// you can also disconnect as well
[cwInterface disassociate];

You can check CoreWLANWirelessManager as a more extensive example.