Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract IP from connection that listen and accept in socket programming in Linux in c

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);
like image 501
Sajad Bahmani Avatar asked Nov 29 '22 11:11

Sajad Bahmani


2 Answers

getpeername()

See the helpful description of how to use it over at the indispensable Beej's Guide to Network Programming.

like image 34
Tyler McHenry Avatar answered Dec 06 '22 22:12

Tyler McHenry


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.

like image 121
Nikolai Fetissov Avatar answered Dec 06 '22 20:12

Nikolai Fetissov