Your
fwrite
call is wrong as it is assuming there are 50 characters in the received message. You should be using the value returned from the call to
recvfrom
thus:
n = recvfrom(sockfd, mesg, 50, 0, (struct sockaddr*)&cliaddr, &len);
fwrite(mesg, 1, n, fp);