Simple (?) UDP sockets question

Robert S. Grimes rsg at alum.mit.edu
Fri May 9 23:21:15 UTC 2008


Synopsis.  Simple question: is it safe to share a single UDP socket 
amongst several tasks?

Details.  My design involves a small number of tasks, each of which is 
responsible for acquiring data and broadcasting the data using UDP 
packets to a single port.  Is it safe to open a socket and share it 
amongst multiple tasks?  Is the networking code sufficiently protected 
such that each UDP packet transmit attempted by a task is sent as 
intended?  I've attempted to look into the networking code, but it is 
rather opaque for me...

Example Code:

    // Open socket
    sId = socket(AF_INET, SOCK_DGRAM, 0);
    assert(sId > 0);

    // Set for broadcasts
    socklen_t opt = 1;
    setsockopt(socketId_, SOL_SOCKET, SO_BROADCAST, &opt, sizeof opt);

    // Init broadcast sockaddr
    destAddr.sin_family = AF_INET;
    destAddr.sin_port = htons(destPort_);
    destAddr.sin_addr.s_addr = htonl(0xffffffff);
    ...


    // Task 1
    while (!done) {
      getSomeTask1Data(buf, &num);
      sendto(sId, buf, num, 0, (struct sockaddr *)&destAddr, sizeof
    destAddr) < 0)
    }


    // Task 2
    while (!done) {
      getMoreTask2Data(buf, &num);
      sendto(sId, buf, num, 0, (struct sockaddr *)&destAddr, sizeof
    destAddr) < 0)
    }

Thanks!
-Bob



More information about the users mailing list