The getpeername function can be used to retrieve the peer IP address and port number on a given socket. For this to work, the socket should have a valid TCP connection established. Typically this is used by server to find the IP address and port number of client. Read more in “Find peer IP address and port number using getpeername” article.
http://www.techpulp.com/articles/networking/snip-find-peer-addr-using-getpeername.php