Reputation: 1
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
Upvotes: 0
Views: 7634
Reputation: 32510
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 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.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);
Upvotes: 0
Reputation: 20654
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.
Upvotes: 1