I'm writing simple server/client and trying to get client IP address and save it on server side to decide which client should get into critical section. I googled it several times but couldn't find proper way to get IP address from sock structure.
I believe this is a way to get IP from sock struct after server accept request from client. More specifically in c after server execute
csock = accept(ssock, (struct sockaddr *)&client_addr, &clen)
Thanks
OK assuming you are using IPV4 then do the following:
If you then want the ip address as a string then do the following:
IPV6 is pretty easy as well ...
and getting a string is almost identical to IPV4
The easier and correct way for extracting IP address and port number would be:
The SoapBox's accepted answer won't be correct for all architectures. See Big and Little Endian.
Assuming
client_addr
is astruct sockaddr_in
(which it usually is). You can get the IP address (as a 32-bit unsigned integer) fromclient_addr.sin_addr.s_addr
.You can convert it to a string this way: