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:
atoi()
is for converting a string value to an integer ... now it seems you already have an integer in the value ofid
, so the argument toatoi()
is incorrect. You would simply need to use something likesprintf()
orsnprintf()
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.- 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 filenetinet/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);
精彩评论