2

I need to pass an integer from a TCP C server with the write() function and receive it in a client with the read() function.

In my server, Let's say

int check = 0

How can I send it with a write() function? I tried on my server:

if (write(connfd, (const char *)&check, 4)) {
    perror("Write Error");
    exit(1);
}

And on my client:

if (n = read(sockfd, &check, 4) > 0) {
    printf("ok");
}

But this method both doesn't work and feels innatural. I understand that I have to pass a buffer everytime but is there a way to speed up things?

Also, the important thing is that I need to create a server/client program with a lot of variables transfer. Can't I pass multiple variable at the same time?

EDIT: When I say it doesn't work I mean that I get "Write Error: Success". connfd and sockfd have been declared previously as the following:

Server:

if ((connfd = accept(listenfd, (struct sockaddr *) NULL, NULL)) < 0) {
    perror("Accept Error");
    exit(1);
}

Client:

if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
    fprintf(stderr,"Connect Error\n");
    exit(1);
}
wiredmark
  • 1,098
  • 6
  • 26
  • 44

1 Answers1

2

You say it doesn't work, what do you mean?

Things you have to keep in mind while sending integers over network is endianness issues, also integers might have different sizes on different computers (but that probably is not issue in your case). You also need a sendall method like this: and also similar readall method.

About your last question indeed you can send say 4 integers over network, you'd just have to copy them to a byte array (unsigned char array) and specify that array in write method call and respective size of the array/data.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
  • Thanks for the answer, I updated the post to answer your question – wiredmark Jan 31 '15 at 17:47
  • @wiredmark: You say "write error: success" but it isn't evident from your code where you print that. Anyway the way you mention now issue might be not in write/read methods, rather how you are setting up connection infrastructure(here is some sample code implementing working server/client in c-maybe you wanna compare your solution against it: http://www.codeproject.com/Tips/834154/Sending-multiple-files-from-server-to-client). – Giorgi Moniava Jan 31 '15 at 17:49
  • What do you mean it is not evident? I get it when trying to write from the server to the client (it's the perror() function I wrote in the post) – wiredmark Jan 31 '15 at 17:52
  • @wiredmark: well, yes but that again suggests me your problem is elsewhere and not in how you use write/read method calls – Giorgi Moniava Jan 31 '15 at 17:53