0

I'm sending an integer array from client to server by socket. Like this ;

int arr[3] = {5, 4, 1};


send(sock , &arr, 3 , 0);   //sending the votes count

and receiving in server like so

recv(new_socket, arr1, 3, 0);

I'm getting correct value in arr1[0] but in arr1[1] I'm getting 66 and arr1[2] I'm getting 67

I don't know how this happening and where 66 and 67 is coming from

internet_user
  • 3,149
  • 1
  • 20
  • 29
Ali Tahir
  • 379
  • 2
  • 14

1 Answers1

2

send() and recv() operate on bytes only. You are sending and receiving 3 bytes, but your array is actually sizeof(int) * 3 bytes instead (where sizeof(int) is usually 4 on many platforms). You need to use sizeof() on both ends, eg:

send(sock, &arr, sizeof(arr), 0);

recv(new_socket, &arr1, sizeof(arr1), 0);

However, you also have to pay attention to return values, because send() can send fewer bytes than requested, and recv() can receive fewer bytes than requested. TCP is stream-oriented, not message-oriented. You should be calling send() and recv() each in a loop, re-calling each one until all expected bytes have been sent/received in full, eg:

ssize_t sendAll(int sckt, void *data, size_t length)
{
    char *bytes = (char*) data;
    while (length > 0)
    {
        ssize_t sent = send(sckt, bytes, length, 0);
        if (sent == -1) return -1;
        bytes += sent;
        length -= sent;
    }
    return 0;
}

int arr[3] = {5, 4, 1};
sendAll(sock, &arr, sizeof(arr));

ssize_t recvAll(int sckt, void *data, size_t length)
{
    char *bytes = (char*) data;
    while (length > 0)
    {
        ssize_t recvd = recv(sckt, bytes, length, 0);
        if (recvd <= 0) return recvd;
        bytes += recvd;
        length -= recvd;
    }
    return 1;
}

int arr1[3];
recvAll(new_socket, &arr1, sizeof(arr1));
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    also a conversion may be needed if endianness of sender/receiver sides are different – Mert Can Ergün Apr 26 '18 at 12:23
  • Seems to be finde. However, I would use `size_t` as type for `length` and `ssize_t` as type for `sent`/`recvd`. It is also a little bit confusing that both functions use different return values. (`sendAll`: 0/OK, -1/IO Error; `recvAll`: 1/OK, 0/Unexpected EOF, -1/IO Error) – JojOatXGME Apr 26 '18 at 12:36
  • @JojOatXGME many of the standard socket functions return 0 on success and -1 on error, so I followed that same convention for `sendAll()`. Since `recv()` has different semantics, `recvAll()` is similarly different. – Remy Lebeau Apr 26 '18 at 14:55