Tuesday, March 18, 2014

[SOCKET] On udp recvfrom peer address return 0.0.0.0:0

ISSUE: When using udp socket it is necessary to know the remote peer address from where the data is received. In future this can be used for sending and tracking messages. If you are ICE or STUN ,TURN developer then its a must.

char recv_data[1024];
int sin_size;
struct sockaddr_in remote_addr;
int bytes_recv = recvfrom(mySock, recv_data,1024,0,(struct sockaddr *)&remote_addr,(socklen_t*)&sin_size);

printf("got packet from IP:Port :: %s:%d\n",inet_ntoa(remote_addr.sin_addr), ntohs(remote_addr.sin_port));  
   

In receiving data which returns remote port and IP as 0.0.0.0:0


Fix: Its happen because the sin_size is not initialize as it takes garbage bellow from system. So just initialize the sin_size will fix that.


 sin_size = sizeof(remote_addr);


So enjoy socket programming :)

2 comments:

  1. Thank you for this answer, this is exactly the problem I was looking for. Indeed after some research we can find in the manpage of the `recvfrom` function : "The argument addrlen is a value-result argument, which the caller should initialize before the call to the size of the buffer associated with src_addr, and modified on return to indicate the actual size of the source address."

    ReplyDelete
  2. Man, thank you very much, exactly the problem I met!!

    ReplyDelete

How to Generate and use the ssh key on Gerrit, github.io, gitlab, and bitbucket.

 Details can be found here -