Can any one please tell me how can we send integers from client to server and add them
in c.
I was able to send strings successfully but i am not able to figure out how to send
integers.
Please help me out!! The below written code was for reading strings. How can i change it
it to read and add integers.
#define SOCK_PATH "echo_socket"
int main(void)
{
int s, t, len;
struct sockaddr_un remote;
char str[100];
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
printf("Trying to connect...\n");
remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, SOCK_PATH);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
int val=connect(s, (struct sockaddr *)&remote, len);
if ( val< 0) {
perror("connect");
exit(1);
}
printf("Connected.\n");
printf("ENTER THE NUMBERS:");
while(printf("> "), fgets(str, 100, stdin), !feof(stdin)) {
if (send(s, str, strlen(str), 0) == -1) {
perror("send");
exit(1);
}
if ((t=recv(s, str, 100, 0)) > 0) {
str[t] = '\0';
printf("echo> %s", str);
} else
{
if (t < 0) perror("recv");
else printf("Server closed connection\n");
exit(1);
}
}
Simple:
The above code sends the integer as is over the socket. To receive it on the other side:
However, be careful if the two programs runs on systems with different byte order.
Edit: If you worry about platform compatibilities, byte ordering and such, then converting all data to strings on one end and then convert it back on the other, might be the best choice. See e.g. the answer from cnicutar.