In the following code I would like to extract the IP address of the connected client after accepting an incoming connection. What should I do after the accept()
to achieve it?
int sockfd, newsockfd, portno, clilen;
portno = 8090;
clilen = 0;
pthread_t serverIn;
struct sockaddr_in serv_addr, cli_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("ERROR opening socket");
}
bzero((char *) & serv_addr, sizeof (serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sockfd, (struct sockaddr *) & serv_addr, sizeof (serv_addr)) < 0)
{
perror("ERROR on binding");
}
listen(sockfd, 5);
clilen = sizeof (cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) & cli_addr, &clilen);
getpeername()
See the helpful description of how to use it over at the indispensable Beej's Guide to Network Programming.
Your cli_addr
already contains the IP address and port of the connected client after accept()
returns successfully, in the same format as your serv_addr
variable. Use inet_ntop
to convert IP to a string.
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