Skip to content

Instantly share code, notes, and snippets.

@dennda
Created September 12, 2011 19:36
Show Gist options
  • Save dennda/1212172 to your computer and use it in GitHub Desktop.
Save dennda/1212172 to your computer and use it in GitHub Desktop.
setupSocket -- no callback
- (void) setupSocket {
struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
// Ask kernel to randomly assign port
addr.sin_port = 0;
void* info = (__bridge void*) self;
readsock = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM,
IPPROTO_TCP, kCFSocketReadCallBack |
kCFSocketAcceptCallBack | kCFSocketDataCallBack |
kCFSocketConnectCallBack | kCFSocketWriteCallBack,
(CFSocketCallBack)&readSockCallBack, info);
CFRunLoopSourceRef sourceRef =
CFSocketCreateRunLoopSource(kCFAllocatorDefault, readsock, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), sourceRef, kCFRunLoopCommonModes);
int readsockfd = CFSocketGetNative(readsock);
int err = bind(readsockfd, (struct sockaddr *) &addr, sizeof(addr));
if (err != 0) {
LOG_NETWORK(8, @"binding readsocket failed due to error %d: %d", err, errno);
assert(0);
}
socklen_t addrLen = sizeof(addr);
// Figure out which port the kernel gave us
err = getsockname(readsockfd, (struct sockaddr *) &addr, &addrLen);
if (err != 0) {
LOG_NETWORK(8, @"Getting socket info failed! %d: %d", err, errno);
}
_port = ntohs(addr.sin_port);
// Backlog of 15
err = listen(readsockfd, 15);
if (err != 0) {
LOG_NETWORK(8, @"Listening on socket failed! %d: %d", err, errno);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment