I was writing a simple C code to create a lisening socket. The code is teh following:
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/ip.h>
void main() {
struct sockaddr_in server;
struct sockaddr_in client;
int clientlen;
char buf[1500];
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
memset((char *)&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(9090);
if(bind(sock, (struct sockaddr *) &server, sizeof(server)) < 0)
error("ERROR on binding");
while(1) {
bzero(buf, 1500);
recvfrom(sock, buf, 1500-1, 0, (struct sockaddr *) &client, &clientlen);
printf("%s\n", buf);
printf("%d - %s\n", client.sin_port, client.sin_addr.s_addr);
}
close(sock);
}
The code compile with no problem but when I connect to the server with a client using netcat:
nc -u 10.0.2.4 9090
and I send some message, the message are replied and then I get the error. DO someone knows why I get this behaviour? Thank you.
There are two main issues here. First,
clientlenis expected to contain the size of the address structure beforerecvfromis called, but it is uninitialized. So set it as follows:Second, you're using
%sto printclient.sin_addr.s_addrbut that field is not a string. You should useinet_ntoato convert astruct inaddr_tto a string: