Does MacOS have a counterpart to Linux's unshare(2)?

I'd like for the following to fail on both systems.

#define _GNU_SOURCE
#include <stdlib.h>
#include <sched.h>
int main()
#if __linux__
    if(0>unshare(CLONE_NEWNET)) return EXIT_FAILURE;
#elif __APPLE__
    //this should fail on either system
    if(0!=system("curl www.google.com")) return EXIT_FAILURE;

Mac OS X doesn't really have namespaces like Linux, but if you want to block networking, it looks like you can use sandbox_init() to get a similar effect. See the man page for a description.

There are two built-in profiles that seem to support a use case similar to what you describe: kSBXProfileNoInternet, where TCP/IP networking is prohibited; and kSBXProfileNoNetwork, where all sockets-based networking is prohibited. (While the latter might be closer to what Linux network namespace is doing here, the former might be enough for your needs.)

Please note that this function is documented as deprecated, and those who wish to sandbox an application should look into the App Sandbox feature, so you might want to take a look at that as well. I don't know that App Sandbox would use the same mechanism (code that you run from a platform #ifdef), that's why I suggested sandbox_init() first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.