clinuxsocketsudpsendto

linux sendto() is flushing buffer?


#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.


Solution

  • 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.