Creating and binding socket on Mac OS Hight Sierra

Viewed 2934

I have serious and strange problem with creating socket in my application for Hight Sierra. If I create command Line tool, everything is ok! I create socket, bind socket. But If I trying to create Cocoa App, I can't binding my socket! :(

If I use CFSockets in Cocoa App,

    char punchline[] = "MESSAGE from Server!";
    int yes = 1;

    CFSocketContext CTX = {0, punchline, NULL, NULL, NULL};

    CFSocketRef TCPServer = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, (CFSocketCallBack) &AcceptCallBack, &CTX);


    if (TCPServer == NULL) return;

    setsockopt(CFSocketGetNative(TCPServer), SOL_SOCKET, SO_REUSEADDR, (void *) &yes, sizeof(yes));

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_len = sizeof(addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(33000);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    NSData *address = [NSData dataWithBytes:&addr length:sizeof(addr)];

    if (CFSocketSetAddress(TCPServer, (CFDataRef) address) != kCFSocketSuccess) {
        CFRelease(TCPServer);
        return;
    }

I get this message:

CFSocketSetAddress bind failure: 1

If I use low level C function in Cocoa App, like this:

  sockfd = socket(AF_INET, SOCK_STREAM, 0);

  bzero((char *) &serv_addr, sizeof(serv_addr));
  portno = atoi(argv[1]);

  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons(portno);

  if (bind(sockfd, (struct sockaddr *) &serv_addr,
             sizeof(serv_addr)) < 0) error("ERROR on binding");

    listen(sockfd,5);
    clilen = sizeof(cli_addr);
    newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

...it's not work too, and I get error on binding and also this message in console:

ERROR: Operation not permitted

But in command line tool everything is working well!

What kind of project settings (may be in info.plist) I need to fix? Where is a trouble? :(

Help me! :(((

2 Answers

The problem was that the application was sandboxed and did not have the Network: Incoming Connections entitlement. That entitlement can be added in Xcode under the App Sandbox details in the Capabilities tab of the target settings.

To Fix it in macOS Catalina Version 10.15.3:

111

Related