Search code examples
iosobjective-cnetwork-programmingudpbsd

why the return value from recvfrom method is 4294967295 which should be 0 or -1?


I am using sendto/recvfrom methods to send/receive UDP packets in my app. Now my receive method is as following:

- (void)listenForPackets
{
    int listeningSocket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (listeningSocket <= 0) {
        NSLog(@"Error: listenForPackets - socket() failed.");
        return;
    }

    // set timeout to 2 seconds
    struct timeval timeV;
    timeV.tv_sec = 2;
    timeV.tv_usec = 0;

    if (setsockopt(listeningSocket, SOL_SOCKET, SO_RCVTIMEO, &timeV, sizeof(timeV)) == -1) {
        NSLog(@"Error: listenForPackets - setsockopt failed");
        close(listeningSocket);
        return;
    }

    // bind the port
    struct sockaddr_in sockaddr;
    memset(&sockaddr, 0, sizeof(sockaddr));

    sockaddr.sin_len = sizeof(sockaddr);
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(18686);
    sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    int status = bind(listeningSocket, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
    if (status == -1) {
        close(listeningSocket);
        NSLog(@"Error: listenForPackets - bind() failed.");
        return;
    }

    // receive
    struct sockaddr_in receiveSockaddr;
    socklen_t receiveSockaddrLen = sizeof(receiveSockaddr);

    size_t bufSize = 9216;
    void *buf = malloc(bufSize);
    size_t result = recvfrom(listeningSocket, buf, bufSize, 0, (struct sockaddr *)&receiveSockaddr, &receiveSockaddrLen);

    NSData *data = nil;

    if (result > 0) {
        NSLog(@"reslut:%zu",result);
        if (result != bufSize) {
            buf = realloc(buf, result);
        }
        data = [NSData dataWithBytesNoCopy:buf length:result freeWhenDone:YES];

        char addrBuf[INET_ADDRSTRLEN];
        if (inet_ntop(AF_INET, &receiveSockaddr.sin_addr, addrBuf, (size_t)sizeof(addrBuf)) == NULL) {
            addrBuf[0] = '\0';
        }

        NSString *address = [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding];
        NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self didReceiveMessage:msg fromAddress:address];
        });

    } else {
        free(buf);
    }

    close(listeningSocket);
}

when i click one button i will send one UDP broadcast and call the above method to listen. At the beginning, i didn't use setsockopt(listeningSocket, SOL_SOCKET, SO_RCVTIMEO, &timeV, sizeof(timeV)) to set a timeout in receive. but when clicked more than once, there will be a bind error.Maybe the first one is still listen the port and not finished. so i add a timeout second to make sure the previous is finished. However, when i set a timeout, the result value in above is 4294967295. and then cause crash in my app. crash log is below:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSConcreteData initWithBytes:length:copy:deallocator:]: absurd length: 4294967295, maximum size: 2147483648 bytes'
*** First throw call stack:
(0x2ed14e83 0x390716c7 0x2ed14dc5 0x2f64799b 0x2f63fe53 0x2f63fd4d 0x2f64dbab 0x2f64db69 0x13cffb 0x13cdb3 0x395560c3 0x3955b7d9 0x3955b9c5 0x39685dff 0x39685cc4)
libc++abi.dylib: terminating with uncaught exception of type NSException

why the return value is 4294967295 instead of 0 or -1 if set a timeout? How to fix this?Any suggestion would be much appreciated.


Solution

  • Use ssize_t not size_t

    int result = recvfrom(listeningSocket, buf, bufSize, 0, (struct sockaddr *)&receiveSockaddr, &receiveSockaddrLen);
    

    size_t is unsigned type, -1 will be cast to 4294967295 (uint_t32). Try this code below:

    uint32_t i = -1 ;
    NSLog(@"%u", i) ; // you get 4294967295
    

    method declares like this:

    ssize_t recvfrom(int socket, void *restrict buffer, size_t length, int flags,
             struct sockaddr *restrict address, socklen_t *restrict address_len);
    

    Thanks to @MartinR for correcting.