There is no elementary way to do this. First, you need some external service that will respond to our request, you can even use the same 2ip, but it is better to find some simpler and more international, for example ipecho.net . Secondly, it will be necessary to interact with the service using some protocol, usually it is http and for this you will need a third-party library or program (option).
The easiest / clumsy way to use wget and popen(3) (error handling is omitted):
#include <stdio.h> // ... char ipaddr[16]; FILE *f = popen ("wget -qO - http://ipecho.net/plain","r"); fnscanf (f, 16, "%s", ipaddr); fclose (f); // в ipaddr получаем адрес в обычной точечено-десятичной форме.
The minus in this approach is dependence on the external program, although it is also a plus: it allows the user to configure the query service at the command level, so if the third-party service stops working, the user will have an easy way to change it.
Alternatives / Further Improvements:
- Of course, you can select any other service for the request.
- You can add non-blocking I / O.
- You can use the libcurl library or some other http client of your choice for requests.
- If you move away from http-based services, that is, for example, opendns.com, which returns the address of the requestor when DNS requests
myip.opendns.com to one of its servers, for example resolver1.opendns.com . those. if you implement everything on low-level sockets, it will be enough to have just one DNS query of the same nslookup myip.opendns.com resolver1.opendns.com .