Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

socket program to add integers in c

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...
");
 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.
");

 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] = '';
 printf("echo> %s", str);
} else 
{
  if (t < 0) perror("recv");
  else printf("Server closed connection
");
  exit(1);
 }

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simple:

int my_int = 1234;
send(socket, &my_int, sizeof(my_int), 0);

The above code sends the integer as is over the socket. To receive it on the other side:

int my_int;
recv(socket, &my_int, sizeof(my_int), 0);

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...