Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the client's IP after receiving a UDP packet with recvfrom() in C?

Tags:

c

udp

Is there a way, as the server, to get the client's IP address as a string after receiving a message from the client with recvfrom()? I would assume it is in the sockaddr_in struct, but I don't know how to access it. Can anyone tell me how I can do this?

like image 965
Mike Weber Avatar asked Nov 06 '13 22:11

Mike Weber


People also ask

Can you use RECV for UDP?

UDP sockets are connectionless and are normally used with the sendto() and recvfrom() calls, although you can also use the connect() call to fix the destination for future packets (in which case you can use the recv() or read() and send() or write() system calls). UDP address formats are identical to those used by TCP.

What will happen when connect () is used in UDP connection in socket programming?

Using the CONNECT command on a UDP socket does not change the UDP protocol from a connectionless to a connection-based protocol. The UDP socket remains connectionless. The primary benefit of using connected UDP sockets is to limit communication with a single remote application.

How do I bind a UDP socket to an IP address?

You would do this with the bind() function: int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); The first parameter is the file descriptor for the socket. The second is a pointer to a socket address structure which contains (for IPv4 or IPv6) the IP address and port to bind to.


1 Answers

The IP address is indeed stored in the struct sockaddr or struct sockaddr_in whose address was passed to recvfrom, and (assuming the structure is named "sender") it can be converted to a string with:

#include <arpa/inet.h>

char* ipString = inet_ntoa(sender.sin_addr);
like image 143
jwodder Avatar answered Oct 11 '22 17:10

jwodder