0

I would like to know how to get the public ip of my server with C programming language.
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).
I've already tried with struct hostent *hp but i get only the local address 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;
}
polslinux
  • 1,739
  • 9
  • 34
  • 73

1 Answers1

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 (i.e. the public address used by the NAT box). What's more, the NAT box might have multiple public addresses.

This happens because your public address is not your address. The public address is just a mirage, i.e. the way outside hosts perceive you. So it makes sense: you can only find it out by asking outside hosts.

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.

Community
  • 1
  • 1
cnicutar
  • 178,505
  • 25
  • 365
  • 392