0
#define BUFSIZE 256
int sockfd;
char buf[BUFSIZE];
struct sockaddr_in server_addr, client_addr;

sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(4100);

while(1){
    printf("to server: ");
    fgets(buf, sizeof(buf), stdin);
    buf[strlen(buf)-1] = '\0';
    sendto(sockfd, buf, BUFSIZE, 0, (struct sockaddr *)&server_addr, sizeof(server_addr);
    //memset(buf, 0, BUFSIZE);
    recvfrom(sockfd, buf, BUFSIZE, 0, (struct sockaddr *)&client_addr, sizeof(client_addr);
    printf("from: %s\n", buf);
}



//SERVER code
#define BUFSIZE 256
int sockfd;
char buf[BUFSIZE];
struct sockaddr_in server_addr, client_addr;

sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(4100);

bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));

while(1){
    recvfrom(sockfd, buf, BUFSIZE, 0, (struct sockaddr *)&client_addr, sizeof(client_addr);
    printf("from client: %s\n", buf);

    printf("to client: ");
    fgets(buf, sizeof(buf), stdin);
    buf[strlen(buf)-1] = '\0';

    sendto(sockfd, buf, BUFSIZE, 0, (struct sockaddr *)&client_addr, sizeof(client_addr);
}

I run two putty on one computer and run the client and server, respectively. The above code is part of the client source.

Run clients and servers respectively, the client sends the message first, and when the server receives the message, it sends a new message to the client. The client prints the message received from the server. (not asynchronous)

The client sends "abcdefg" to the server and receives "zxc" from the server. Then, when I output the buffer, it prints only "zxc" instead of "zxcdefg".

I am wondering why the output looks like this even though I did not call the memset() method.

bean123456
  • 15
  • 5

1 Answers1

0

You haven't posted the server code, but if it's like this client code you're always sending BUFSIZE characters, irrespective of the string length.

If the string zxc sent by the server is NUL terminated, then that's how it'll look when received by the client. There will be (invisible) trailing garbage in the received buffer, too.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • Is there a "zxcNULLefg" stored in the client's buffer? So when outputting a buffer, does it print only up to "zxc"? – bean123456 Dec 04 '18 at 09:28
  • @H.Bin that's my hypothesis, although strictly speaking the `\0` character is called `NUL`, not `NULL`. To know for sure I'd need to see your server side code too. – Alnitak Dec 04 '18 at 09:30
  • I have added a portion of the server code. By setting the value of '\ 0' in the server code, I think you are right. Thank you very much. – bean123456 Dec 04 '18 at 09:39