How to listen on all interfaces with TCPListener? [solved]


#1

All the examples I see listen on 127.0.0.1, which is nice for an example code, but less nice if you want to communicate between listeners. How do we listen on every port?

The documentation doesn’t say…

[edit] It looks like specifying an IP address of “0.0.0.0” works.


#2

You’ve figured it out, but just wanted to say that https://doc.rust-lang.org/std/net/struct.Ipv4Addr.html#method.is_unspecified is where this is better documented, along with more methods there. Similarly for ipv6.


#3

Thanks, @vitalyd! This is definitely a place where the documentation might be improved. One wouldn’t necessarily look at the Ipv4Addr documentation to find what would ideally not be an IPv4 thing! Which leads me to a related question: is there a way to listen on both IPv4 and IPv6?


#4

Yes, it’s called “dual stack” mode. It’s somewhat platform specific. If you’re on linux and dual stacking is enabled, you can try binding to “[::]:0” (the ANY addr for ipv6), and it’ll listen for IPv4 connects as well.