Objective-C: Check Firewall status in OSX?

痞子三分冷 提交于 2020-07-18 15:56:22

问题


My objective-c app needs to be aware if the firewall in OSX is running, so it can tell the user to turn it off or create a new rule.

Also, is it possible to create rules directly from my app so users never need to handle networking issues?

John


回答1:


I am writing a function that will provide you the status of OSX firewall :)

-(BOOL)getFirewallStatus{


    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSSystemDomainMask, YES);

    NSString *path = [paths objectAtIndex:0];

    path = [NSString stringWithFormat:@"%@/%@",path,@"Preferences/com.apple.alf.plist"];

    path = [path stringByReplacingOccurrencesOfString:@"/System"
                                           withString:@""];




    NSDictionary* _dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:path];


    // firewall status
    int status = [[_dictionary valueForKey:@"globalstate"] integerValue];

    if (status == 0)
    {
        return NO;
    }

    return  YES;
}



回答2:


If your application is being run by the user (i.e., double-clicked in the Finder), any attempt by your application to create a socket listener will prompt the user to allow/deny that listener - and subsequently adjust the firewall settings accordingly - without any programmatic intervention on the part of your application.

If the firewall in question is your router (a problem I recently had to deal with), you have a few options. The best supported option is Bonjour/mDNSResponder (as long as you don't want to support a double-nat'ed situation). Apple provides an Objective-C wrapper application around the rather obtuse dns_sd.h:

http://developer.apple.com/library/mac/#samplecode/PortMapper/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007879-Intro-DontLinkElementID_2

Going the 3rd party route, take a look at TCM Port Mapper. It uses some deprecated features and it'll take a bit of effort to get it running with ARC support (if that's important to you).

http://code.google.com/p/tcmportmapper/

Both support UPnP and NAT-PMP.

Finally, if your application is running as a daemon (without a user interface), you're going to have to become acquainted with ipfw. Brace yourself. Google for "ipfw os x". StackOverflow is preventing me from posting more than two links. Brilliant.

Hope this helps....



来源:https://stackoverflow.com/questions/4699349/objective-c-check-firewall-status-in-osx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!