Closed Shatur closed 2 years ago
Thanks! I noticed a few people confused about this, this simplification will help. :)
I'm not sure if this works for windows, or is there something I'm missing here?
It works in the case of local IP, but you can't bind to a public ip.
I'm not sure if this works for windows, or is there something I'm missing here?
What https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html#method.local_addr returns for you?
@Shatur
In this code:
use std::net::UdpSocket;
pub fn main() {
let socket = UdpSocket::bind("192.168.0.110:0").unwrap();
dbg!(socket.local_addr());
let local_socket = UdpSocket::bind("127.0.0.1:0").unwrap();
dbg!(local_socket.local_addr());
}
it outputs:
[sabi\examples\test.rs:5] socket.local_addr() = Ok(
192.168.0.110:49958,
)
[sabi\examples\test.rs:7] local_socket.local_addr() = Ok(
127.0.0.1:49959,
)
However the server addr for the first needs to be my public ip which is 76.176.12.210
otherwise the clients will have issues connecting since it will compare their connect token against the 192.168.0.110
rather than 76.176.12.210
It works in the case of 127.0.0.1
because I connect to the server using 127.0.0.1
. But the ip for binding and the public ip are different for when the server is exposed.
it outputs:
It's totally expected output. You need to use 76.176.12.210
as your address.
That isn't a valid bind address though? At the very least for windows.
Replacing 192.168.0.110 with 76.176.12.210 makes it error out with this:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 10049, kind: AddrNotAvailable, message: "The requested address is not valid in its context." }', sabi\examples\test.rs:4:53
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Hm... So with the previous approach (when we had separate addresses) you was able to bind local adress and connect from the internet using public address?
Ya
Hm... Okay, let's revert this change. Could you send a PR?
Will do, although I do agree that it is a bit confusing so might be good to figure out some sort of common error checking for the addresses.
BTW, what https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html#method.peer_addr returns for you?
I think that only returns something when you do .connect("...")
for the UdpSocket, did check that though, not sure if I'm missing a method on the socket docs for a public addr or something
I believe this will make server creation less error-prone. It also makes it easier to use
0
for port to let the system pick one, sincelocal_addr()
returns the actual port used.