Skip to content

Instantly share code, notes, and snippets.

@beccadax
Created April 12, 2013 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beccadax/5369045 to your computer and use it in GitHub Desktop.
Save beccadax/5369045 to your computer and use it in GitHub Desktop.
Category on NSSocketPort to create ports bound only to `localhost`, and thus only accessible to other processes on the same Mac.
//
// NSSocketPort+initWithLocalhostTCPPort.h
// Typesetter
//
// Created by Brent Royal-Gordon on 4/10/13.
// Copyright (c) 2013 Groundbreaking Software. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSSocketPort (initWithLocalhostTCPPort)
- (instancetype)initWithLocalhostTCPPort:(unsigned short)port;
@end
//
// NSSocketPort+initWithLocalhostTCPPort_.m
// Typesetter
//
// Created by Brent Royal-Gordon on 4/10/13.
// Copyright (c) 2013 Groundbreaking Software. All rights reserved.
//
#import "NSSocketPort+initWithLocalhostTCPPort.h"
#import <sys/socket.h>
#import <netinet/in.h>
@implementation NSSocketPort (initWithLocalhostTCPPort)
- (instancetype)initWithLocalhostTCPPort:(unsigned short)port {
NSMutableData * addr = [NSMutableData dataWithLength:sizeof(struct sockaddr_in)];
struct sockaddr_in * localhost = addr.mutableBytes;
localhost->sin_len = sizeof(struct sockaddr_in);
localhost->sin_family = PF_INET;
localhost->sin_port = htons(port);
localhost->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
return [self initWithProtocolFamily:PF_INET socketType:SOCK_STREAM protocol:IPPROTO_TCP address:addr];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment