Search code examples
carrayssocketsint

How to send integer array over udp socket in C?


I have to send an int array over an udp socket. Do I have to convert it as char array or as a sequence of byte? What is the standard solution?


Solution

  • You could just do as follow:

    int array[100];
    sendto(sockfd, array, sizeof(array), 0, &addr, addrlen);
    

    To recv your array the other side (assuming you always send array of the same size):

    int array[100];
    recvfrom(sockfd, array, sizeof(array), 0, &addr, &addrlen);
    

    As said in the comments, you have to be carefull about the architecture of the system which send / receive the packet. If you're developping an application for 'standard' computers, you should not have any problem, if you want to be sure:

    • Use a fixed-size type (include stdint.h and use int32_t or whatever is necessary for you.
    • Check for endianess in your code.

    Endianess conversion:

    // SENDER   
    
    int32_t array[100] = ...;
    int32_t arrayToSend[100];
    for (int i = 0; i < 100; ++i) {
        arrayToSend[i] = htonl(array[i]);
    }
    sendto(sockfd, arrayToSend, sizeof(arrayToSend), 0, &addr, addrlen);
    
    // RECEIVER
    
    int32_t array[100];
    int32_t arrayReceived[100];
    recvfrom(sockfd, arrayReceived, sizeof(arrayReceived), 0, &addr, &addrlen);
    for (int i = 0; i < 100; ++i) {
        array[i] = ntohl(arrayReceived[i]);
    }