Seeking a simple way to detect my ip

I have downloaded local-ip-address = "0.4.4" crate.
It works great but shows a bunch of ips. And I will have to iterate to select I need. I am not big expert network interfaces.

Python does it in very easy way:

socket.gethostbyname(socket.gethostname())

if it crashes - there is no internet connection
if it shows ip - connection is established
if ip starts which 10 - vpn is established

Not really. I can be connected to my router, while my router can be disconnected from the internet. The Python call you mentioned will succeed regardless.
In general, the only real way to check for internet connection is to make a connection to some website that you know is outside your local network.
So roughly speaking, try making a HEAD request to some well known website - make sure to not spam it though, otherwise you may end up getting flagged by a load balancer, and the connection will fail.

1 Like

I suggest using a service like ipify, using a crate like reqwest

3 Likes

That's because your computer doesn't just have one IP address, it's got many IP addresses which are all equally valid.

For example, my desktop currently has half a dozen IP addresses - localhost (127.0.0.1), my WiFi connection (e.g. 192.168.1.123), my ethernet port, 5 running docker containers, my VPN, and so on.

The WiFi is the one I would normally care about when trying to SSH in from another device on my network because that's the one connected to my router, but there isn't anything innately special about this network interface as far as the OS is concerned.

That's also not mentioning the fact that my desktop is connected to my router, which does Network Address Translation and has its own IP address that the wider internet sees (often referred to as your "public IP address").

I think once you define "my ip" more precisely you'll have a better idea of how to get the IP address that is relevant to you.

3 Likes

I do it. When I am in vpn. I use http://checkip.dyndns.com. And now I am going to rewrite it in Rust. According responses I am in right way - local-ip-address is what I need. Thank You All.

Ah, if that's the case you can use the reqwest crate and either reqwest::blocking::get() or reqwest::get() to send a request to dyndns.com then read your IP address out of the response.

1 Like

Thank You..
I will use local-ip-address for local ip
And will use reqwest and http://dyndns.com/ for vpn ip and for study web scraping
And additionaly will use https://www.ipify.org/ for practice working with API

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.