c - 如何在 Linux 系统中使用 C 而不是 localhost 地址获取实际客户端 IP
问题描述
我正在尝试使用 C 代码读取 ubuntu 系统中的 IP 地址
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char **argv) {
int status;
struct addrinfo hints, *p;
struct addrinfo *servinfo;
char ipstr[INET_ADDRSTRLEN];
char hostname[128];
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
gethostname(hostname, 128);
if ((status = getaddrinfo(hostname, NULL, &hints, &servinfo)) == -1) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(1);
}
for (p=servinfo; p!=NULL; p=p->ai_next) {
struct in_addr *addr;
if (p->ai_family == AF_INET) {
struct sockaddr_in *ipv = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv->sin_addr);
}
else {
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = (struct in_addr *) &(ipv6->sin6_addr);
}
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
}
printf("Address: %s\n", ipstr);
freeaddrinfo(servinfo);
return 0;
}
我没有得到实际的客户端 IP,而是得到 127.0.1.1 而我期待 192.168.xx 当我在 /etc/hosts 文件中评论 127.0.1.1 时,我得到了实际的 IP,但这个解决方案不可行
解决方案
推荐阅读
- jquery - 如何删除/替换输入的表情符号?
- google-bigquery - BigQuery - 获取叶行的递归查询
- arrays - 在表达式中使用时数组转换为指针
- linux - Unix find 命令以千兆字节显示文件大小
- rabbitmq - RabbitMQ 服务器配置为不同消费者服务多个同名队列
- java - 通过 Java 在单独的账户中从 lamba 调用 AWS lambda
- php - 在 Laravel 8.x 中循环嵌套注释
- reactjs - 使用反应路由器时,如何在 iframe 中使用反应应用程序提供静态 html 文件?
- python - 运行python模块时如何附加到vscode调试器?
- java - java.lang.NoClassDefFoundError:无法初始化类 sun.security.provider.SecureRandom$SeederHolder