开发者

read integer through a socket c

i need to read an integer through a socket and the sens it to a function. i do

strcpy(out,"insert id messagge\n");
if (write(sd_client,out, sizeof(out))==-1){
    printf(开发者_如何转开发"Error.\n");
    }
while ((read(sd_client, &id, sizeof(int)))==-1){  //id is an integer
        if(errno!=EINTR){
    printf("Error.\n");
        exit(-1);
    }
}
messaggio2(sd_client, logi, atoi(id)); //atoi(id) try to send int to func

someone can help me please? :D


The second parameter of read and write is a pointer to the data.

When you say:

write(sd_client,out, sizeof(out))

you're passing the value of out. That should be:

write(sd_client, &out, sizeof(out))

Also, I think that you've declared id as int (which is correct), so why are you passing it to atoi? That function is for parsing a int from a string.


The problem you're having seems a bit vague since you haven't actually mentioned the errors you're getting, but from the code you have posted, it seems like you are running into two different problems:

  1. atoi() is for converting a string value to an integer ... now it seems you already have an integer in the value of id, so the argument to atoi() is incorrect. You would simply need to use something like sprintf() or snprintf() to convert your integer value to a string value and then copy that into a user-defined string-buffer if you are wanting a string-representation of your integer.
  2. You are working with sockets, therefore any information transferred over the network will be coming in network-byte-order. If you are on a little-endian platform, then the integer will be coming in a big-endian format, and you will be interpreting the value of your integer incorrect. Therefore you should be converting your integer to the native platform endian format using a function like ntohl() which can be found inside of the header file netinet/in.h

So for instance:

#include <netinet/in.h>

int id;
int sd_client;

//... code to open socket, etc.

//add your own error-checking ... stripped out here for simplicity's sake
read(sd_client, &id, sizeof(int));
id = ntohl(id);

char buffer[32];
snprintf(buffer, sizeof(buffer), "%d", id);
messaggio2(sd_client, logi, buffer);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜