I have a server program. I get to connect to it for all 3 ip:

127.0.0.1 locally

192.168.1.3 router

109.127.85.64 Internet

I could only make UDP work.

How can I find my IP address on the network? (I need the program, I can find it on 2ip). Maybe through some resource you can? Or some special function. On Linux is necessary.

  • There in English and very much. I would have a simple function int32_t getip (); or in Russian at least a description. - Nikita Samoukov

1 answer 1

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 .