Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the first client sees to have source ip of 0.0.0.0?

Tags:

c

linux

sockets

udp

I have a client.c server.c on linux. on both I init a socket:

sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)

in the server I add:

listen_addr.sin_family = AF_INET;
listen_addr.sin_port = htons(port);
listen_adrr.sin_addr.s_addr = htonl(INADDR_ANY);

the server.c calls (blocking way) to recvform:

if (recvfrom(sockfd, buf_get, BUFLEN, 0, (struct sockaddr*)&talker_addr, &slen) == -1)
            err("recvfrom()");

And the client.c sends packets with:

if (sendto(sockfd, buf_sent, BUFLEN, 0, (struct sockaddr*)&serv_addr, slen) == -1)
        err("sendto()");
  1. The problem is that on the first calling to sendto from client.c, the servers sees the client's ip as 0.0.0.0, after that on the second, third,... calls the client.c get an ip and have a legal ip such as 127.0.0.3:3212.
  2. another weird thing is that if I start a second new client it gets ip from the first time.
like image 774
0x90 Avatar asked May 13 '13 09:05

0x90


1 Answers

Make sure you are setting slen to the size of the talker_addr struct before you call recvfrom. It will set the value (which may explain why it works in subsequent calls) in recvfrom but if there is a bad initial value, you may get garbage the first call.

slen = sizeof(struct sockaddr_in);
like image 199
xaxxon Avatar answered Oct 06 '22 00:10

xaxxon