简体   繁体   English

在C套接字中获取客户端的IP地址

[英]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? 如何获取服务器所连接的客户端的IP地址? 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. 但是我得到的不是我的IP地址127.0.0.1。 Could it have something to do with me using localhost to test my client and server? 使用本地主机测试我的客户端和服务器可能与我有关吗?

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. 该连接不是通过Internet进行的,不涉及网络硬件,客户端数据包将来自本地主机。 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. 如果客户端要使用服务器的外部IP地址连接到服务器,则它将必须通过外部路由进行连接,因此需要可路由的IP地址。 For example, I can connect to a server on localhost, but I cannot using my routable IP address because my router blocks incoming connections. 例如,我可以连接到localhost上的服务器,但由于路由器阻止传入连接,因此无法使用可路由的IP地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM