coder4lyf
coder4lyf

Reputation: 927

Get IP address of the client in C sockets

How can I get the ip address of the client of which my server is connected to? Here is how I accept incoming clients:

newsockfd = accept(sockfd, (struct sockaddr*)&clt_addr, &addrlen);

I tried the following:

 printf("ip is: %s\n", inet_ntoa(clt_addr.sin_addr));

But I am getting 127.0.0.1 which is not my ip address. Could it have something to do with me using localhost to test my client and server?

Upvotes: 0

Views: 4342

Answers (1)

Schwern
Schwern

Reputation: 165416

Could it have something to do with me using localhost to test my client and server?

Yes. If you connect to a server on localhost the client will also be localhost. This connection is not happening over the Internet, there is no network hardware involved, the client packets will come from localhost. This is known as loopback and occurs entirely in software.

If the client were to connect to the server using the server's external IP address it will have to do a connection via external routing and thus require a routable IP address. For example, I can connect to a server on localhost, but I cannot using my routable IP address because my router blocks incoming connections.

Upvotes: 2

Related Questions