0

i am haveing trouble transferring int array over socket in c. what is the correct use of htonl()? lets say i have :

int arra[3]={6000,7000,8000};

and socket called new_socket

how do i transfer it correctly to the other end of socket?

client is reading it by the following code:

char buf[BUFLEN] = "";  // buffer for recv() calls

for (i = 0; i < nbytes; i += INTLEN) {
    int file_port = ntohl(*(int *)&buf[i]);
chrk
  • 4,037
  • 2
  • 39
  • 47
Ohad Gerrassy
  • 116
  • 11
  • Enumerate the array on the sender side revamping via `htonl` *before* sending, and again after *complete* reception on the receiver side using `ntohl`. It looks like you *almost* have second half of it down already. – WhozCraig Jul 15 '14 at 10:52
  • i cannot modify the client with is waiting for a buffer and takes the int from it, still couldnt understand how to implement the server – Ohad Gerrassy Jul 15 '14 at 11:48
  • Your question appears to be about what to "do" with the `arra` array before sending it. To that end, I told you. The responsibility of the actual socket-work is a totally unrelated issue. You should also be aware that this design assume `int` is the same bit-width on both the client and server; something that can likely *not* be true if the client-side is truly portable. best of luck. – WhozCraig Jul 15 '14 at 11:56

1 Answers1

0
   int i, wp1, ret;
   for (i = 0; i < 3; i++) {
      wp1 = htonl(arr[i]);
      ret = write(sockfd, wp1, sizeof(int));
      //error check based on ret
   }

this works. TCP is a stream, one write or multiple writes doesn't matter, you can read it all in one go or read until you have necessary number of bytes and do paste the entire program in either side and the output you are getting

Nish
  • 379
  • 2
  • 9