Instantly share code, notes, and snippets.

What would you like to do?
Disables Nagle's Algorithm on a TCP socket
// Nagle's algorithm is a means of improving the efficiency of TCP/IP networks by reducing the number of packets that need to
// be sent over the network.
#import <netinet/in.h>
#import <netinet/tcp.h>
@implementation NSStream (DisableNaglesAlgorithm)
- (void)disableNaglesAlgorithmWithError:(NSError **)error {
CFDataRef data;
// Get socket data
if ([self isKindOfClass:[NSOutputStream class]]) {
data = CFWriteStreamCopyProperty(
(__bridge CFWriteStreamRef)((NSOutputStream *)self),
} else if ([self isKindOfClass:[NSInputStream class]]) {
data = CFReadStreamCopyProperty(
(__bridge CFReadStreamRef)((NSInputStream *)self),
// get a handle to the native socket
CFSocketNativeHandle handle;
CFDataGetBytes(data, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8 *)&handle);
// Disable Nagle's algorithm
int err;
static const int kOne = 1;
err = setsockopt(handle, IPPROTO_TCP, TCP_NODELAY, &kOne, sizeof(kOne));
if (err < 0) {
err = errno;
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{
NSLocalizedDescriptionKey : @"Error disabling Nagle's algorithm"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment