简体   繁体   English

c获取服务器公共IP

[英]c get server public ip

I would like to know how to get the public ip of my server with C programming language. 我想知道如何使用C编程语言获取服务器的公共IP。
I already know how to do this with libcurl but now i want to understand how to get this info with the socket programming (if it is possible) . 我已经知道如何使用libcurl做到这一点,但现在我想了解如何通过套接字编程(如果可能)获取此信息。
I've already tried with struct hostent *hp but i get only the local address 127.0.0.1 我已经尝试过使用struct hostent *hp但仅获得本地地址127.0.0.1
This is the code i've used: 这是我所使用的代码:

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;
}

You can't do it on your own, there's no reliable way. 您不能自己做,没有可靠的方法。 Let's say you're behind a NAT box: you can never know the inside global address (ie the public address used by the NAT box). 假设您位于NAT框后面:您永远无法知道内部全局地址(即NAT框使用的公共地址)。 What's more, the NAT box might have multiple public addresses. 此外,NAT框可能有多个公共地址。

This happens because your public address is not your address . 发生这种情况是因为您的公共地址不是您的地址 The public address is just a mirage, ie the way outside hosts perceive you . 公共广播只是海市rage楼,即外面的主人看待你的方式 So it makes sense: you can only find it out by asking outside hosts. 所以这很有意义:您只能通过询问外部主机来找到它。

TLDR TLDR

Do a request to an outside host: 向外部主机发出请求:

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

It is trivial to do it using libcurl or with your own sockets. 使用libcurl或使用您自己的套接字执行此操作很简单。

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

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