wiredmark
wiredmark

Reputation: 1108

Correct way to write/read integers in C socket programming

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);
}

Upvotes: 2

Views: 1562

Answers (1)

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

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.

Upvotes: 2

Related Questions