3

According to the documentation, TcpListener and UdpSocket will be automatically closed when the value is dropped/out of scrope. But why is there no shutdown method to let me manually close them?

https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html

1
  • 1
    You can manually drop() it. There isn't any reason why keeping around a handle to a closed socket should be possible.
    – Ivan C
    Commented Jul 23, 2021 at 22:42

3 Answers 3

8

You can use std::mem::drop to drop a value early:

let listener = TcpListener::bind("127.0.0.1:80")?;
// ...
drop(listener);
// ...

There is no shutdown method because it isn't needed. The existing ownership system is already good enough for keeping track of if a socket is usable, and there is nothing you can do with a closed socket anyways.

1
  • 2
    That not why there is no shutdown method on TcpListenr, see answer from iggy.
    – Stargateur
    Commented Jul 24, 2021 at 9:27
7

You confuse TcpListener and TcpStream.

'shutdown' in TCP sockets has a technical meaning. Shutdown on the send side transmits a FIN to the remote. Shutdown on the receive side means that any arriving data segments will get a RST response. These definitions are only applicable to a TCP connection in data transfer state, not to listening sockets.

5
  • So what? Local resources, such as the open socket, still have to be cleaned up. I don't know where you picked up this "meaning", but in *nix systems it simply lets you to shut down read/recv of the socket.
    – Kaihaku
    Commented Jul 24, 2021 at 7:53
  • @Stargateur What does this have to do with what I wrote?
    – Kaihaku
    Commented Jul 24, 2021 at 9:26
  • @Stargateur 5 words that completely change the meaning of original answer which has nothing to do with my original comment.
    – Kaihaku
    Commented Jul 24, 2021 at 9:40
  • @Kaihaku - ever looked at what actually happens when you call shutdown() on a TCP socket under Unix? Local kernel resources are cleaned up by a close(),, not shutdown(). Most layered APIs then make their shutdown methods call shutdown() on the socket, since doing otherwise would be surprising. I confess, however, to not having noticed this was a Rust-specific question, about which I have no direct knowledge.
    – iggy
    Commented Jul 24, 2021 at 11:39
  • @Kaihaku - the 5 words do not change the intended meaning of my answer. They add a worthwhile clarification of my point.
    – iggy
    Commented Jul 24, 2021 at 11:50
0

You can manually close a listener simply by explicitly dropping:

drop(listener);

Not the answer you're looking for? Browse other questions tagged or ask your own question.