How can I refuse a socket connection in C?

后端 未结 5 540
感情败类
感情败类 2021-01-01 14:03

If I want to accept a connection I call accept, but how can I refuse a connection?

In a working socket echo client I have this if statement. In the echo

5条回答
  •  悲&欢浪女
    2021-01-01 14:08

    To get the behavior you want (only accept one connection at a time, other clients attempting should get a failure), there are two choices.

    • You can close your listen socket after you have accepted a connection. Re-create your listen socket after the accepted connection closes.

    • You can close newly established connections if there is already a connection in progress. If you want the client to see a TCP reset, most TCP stacks will trigger one if you enable the linger option with a timeout of 0.

      struct linger lo = { 1, 0 };
      setsockopt(s, SOL_SOCKET, SO_LINGER, &lo, sizeof(lo));
      close(s);

提交回复
热议问题