[Solved] How to get my external ip (primary interface) without internet connection, without eth0 and without any hardcoded constnts using C [closed]


If you just want to discover the default adapter’s assigned IP address, e.g. 192.168.0.237, call getifaddrs and enumerate each address. This is the same list of adapters that ifconfig would normally display with associated information for gateway and netmask. Filter out the ones that are flagged as IFF_LOOPBACK or don’t have IFF_UP. Some sample code here.

If you have more than one such address, then you need to check the route table and find the default route (the one with a target IP address of 0.0.0.0).

jselbie@ubuntu:~$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.254.2   0.0.0.0         UG    100    0        0 ens33
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 ens33
192.168.254.0   0.0.0.0         255.255.255.0   U     100    0        0 ens33

The first entry, the one with the destination route of 0.0.0.0, is your default route and sends through the ens33 adapter. If there was more than one default route, you would use the one with the lower metric field. In my case, the interface of the 0.0.0.0 route is ens33. The IP address of ens33 can be discovered through a call to getifaddrs as described above. (reference the ifa_name field in the enumerate list of ifaddrs.)

As for programatically enumerating the routing table in C, I actually don’t remember how to do this. A quick internet search suggests you can get using a NETLINK socket. I would consult that source code for the route command as well.

7

solved How to get my external ip (primary interface) without internet connection, without eth0 and without any hardcoded constnts using C [closed]