首页 > 解决方案 > 如何在 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,但这个解决方案不可行

标签: clinuxubuntunetwork-programmingip

解决方案


推荐阅读