Comment by scottlamb
I agree with everything you wrote except for this:
> Indeed, in the general case some perfectly coded `unsafe` code could `dup2()` over the fd, so any checking at UdpSocket creation time is moot; you still don't get the safety you are asking for.
If `unsafe` code breaks safe code's soundness guarantees (let's assume for a second an alternate world in which "fd is of the correct type" is a soundness guarantee Rust makes), the bug is in the `unsafe` code.
Sure, I would strongly recommend against doing something like that. But I would expect it to work in the obvious way, and not be undefined behavior.
E.g. if UdpSocket were to dup() internally its fd A into a fd B, and as_fd() returned B, but all actual recv/send is on fd A, then that would cause worse problems than this.
But say an OS has a sockopt that turns an IPv4 UDP socket into a IPv6 UDP socket. Would it be OK for me to call that on UdpSocket's underlying fd? I'd say yes.
Now if I closed the fd for a UdpSocket from underneath it, I would expect that to be basically UB, if not by spec, then in practice impossible to reason about.
As for unsound, sure. I could be convinced of calling the dup2 thing unsound. Not sure unsound is well enough defined, but basically: don't do it.
Is it unsound to create a UdpSocket from a non-UDP file descriptor? Not in a way that can trigger unsafe, no.