绑定/侦听Mac OSX Lion 10.7.2中的端口失败

时间:2011-11-20 00:41:51

标签: cocoa sockets listener port cfsocket

我正在尝试在MacOSX 10.7.2(Lion)下设置SilverLight策略服务器。这要求我创建套接字并将其绑定到端口943,因为SilverLight在此端口上请求策略文件。不幸的是,似乎我无法在该端口绑定,因为绑定调用失败errno=49.我想我无法访问此端口。也许我需要root权限?或者我是否需要将此端口转发到另一个我可以绑定的端口?我对网络编程有点新意,所以非常感谢任何帮助!我还附上了我的源代码。也许我做错了,虽然如果我使用SilverLight受限端口4502-4532就可以正常工作,SilverLight会在成功提供策略文件后进行通信。

- (void) start {
    CFSocketRef socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, 0, NULL, NULL);
    if (!socket) {
        [self errorWithName:@"Unable to create socket."];
        return;
    }

    int reuse = true;
    CFSocketNativeHandle fileDescriptor = CFSocketGetNative(socket);
    if (setsockopt(fileDescriptor, SOL_SOCKET, SO_REUSEADDR,
                   (void *)&reuse, sizeof(int)) != 0) {
        NSLog(@"Unable to set socket options.");
        return;
    }

    struct sockaddr_in address;
    memset(&address, 0, sizeof(address));
    address.sin_len = sizeof(address);
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    address.sin_port = htons(943);
    CFDataRef addressData = CFDataCreate(NULL, (const UInt8 *)&address, sizeof(address));
    [(id)addressData autorelease];

    CFSocketError error = CFSocketSetAddress(socket, addressData);
    if (error < 0) {
        NSLog(@"Error bind %d\n", errno);  //fails here for port 943.
        return;
    }

    NSFileHandle *listeningHandle = [[NSFileHandle alloc]
                   initWithFileDescriptor:fileDescriptor
                   closeOnDealloc:YES];

    [[NSNotificationCenter defaultCenter]
          addObserver:self
             selector:@selector(receiveIncomingConnectionNotification:)
                 name:NSFileHandleConnectionAcceptedNotification
               object:nil];

    [listeningHandle acceptConnectionInBackgroundAndNotify];
}

1 个答案:

答案 0 :(得分:2)

只有root拥有1024以下端口的权限。尝试使用sudo运行您的代码,看看是否能解决您的问题。

编辑:

另外,请查看man strerror。它将采用相对无意义的错误代码,并为您提供(稍微)更有用的字符串。

#include <stdio.h>
#include <string.h>

int main (int argc, char const *argv[])
{
  printf("%s\n", strerror(49) );
  return 0;
}

给出:

Can't assign requested address