c 获取服务器公共(public)IP

标签 c sockets ip

我想知道如何使用 C 编程语言获取服务器的公共(public) ip。
我已经知道如何使用 libcurl 执行此操作,但现在我想了解如何使用套接字编程获取此信息(如果可能的话)
我已经尝试过 struct hostent *hp但我只得到本地地址 127.0.0.1
这是我使用过的代码:

int main(int argc, char *argv[]){
    struct hostent *hp;
    int i=0;
    if((hp=gethostbyname(argv[1])) == NULL){
        herror("gethostbyname()");
        exit(1);
    }
    fprintf(stdout, "Hostname: %s\n", hp->h_name);
    /* fprintf (stdout,"IP server: %s\n",inet_ntoa(*((struct in_addr *)hp->h_addr))); con questa printo solo 1 ip */
    while (hp->h_addr_list[i] != NULL) { /* mentre così printo tutti gli eventuali ip */
        printf("IP: %s\n", inet_ntoa(*(struct in_addr*)(hp->h_addr_list[i])));
        i++;
    }
    return 0;
}

最佳答案

你无法自己做到这一点,没有可靠的方法。假设您位于 NAT 框后面:您永远无法知道内部全局地址(即 NAT 框使用的公共(public)地址)。此外,NAT 盒可能有多个公共(public)地址。

发生这种情况是因为您的公共(public)地址不是您的地址。公共(public)地址只是一个海市蜃楼,即外部主机感知您的方式。所以这是有道理的:你只能通过询问外部主机来找到它。

TLDR

向外部主机发出请求:

[cnicutar@fresh ~]$ curl ifconfig.me
192.0.2.42

使用 libcurl 或使用您自己的套接字来完成此操作很简单。

关于c 获取服务器公共(public)IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12155199/

相关文章:

c - typedef 和 struct 的语法错误?

C99 boolean 数据类型?

c - 将字符数组指定为函数参数的正确语法是什么?

Python正则表达式单词、ip和端口组合匹配

linux - 树莓派有静态IP地址

c - 请解释这段代码中运算符的结合性

python - 操作系统错误: [Errno 48] Address already in use

java - 如何提高读取 InputStream 的性能?

java - 我真正需要多少个线程?

c - 迷你拼图 IP header