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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With