开发者

TcpListener: Reject an incoming connection request before connection

I have a service that's open to everyone on the public internet. It runs TcpListener to manage incoming connections.

The service maintains a list of persistently misbehaving clients by their incoming IP address.开发者_开发问答 Any connections coming from a listed IP are sent a "go away" message as the connection is closed down.

I'd prefer it if the socket isn't opened in the first place, but by the time AcceptTcpClient has returned, the connection is already opened.

Is there a way for my code to step in and examine incoming connection requests (and perhaps reject them) before they are opened?

Many thanks.


WSAAccept allows specifying a callback which can decide whether to accept or reject a connection. See this question for how to call it from C#.


Since you're using .Net I assume you must be running under Windows.

There is no way from the sockets API to do what you seek. However, you could have your program add Windows Firewall rules to accomplish the same thing -- assuming you have Windows Firewall turned on.


For anyone looking for a solid answer to this still:

TcpListener inListener;
bool _canClientConnect = true;
TcpClient _client;

if (_inListener != null && _inListener.Pending() && _canClientConnect) { // Accept actual client
    _canClientConnect = false;
    _cancelTokenSource = new CancellationTokenSource();
    _client = _inListener.AcceptTcpClient();
    _stream = _client.GetStream();
    if (_recieverTask != null) {
        _recieverTask.Start();
    }
}
if (_inListener.Pending() && !_canClientConnect) { // Client found connecting, but we are already connected.
    _inListener.AcceptTcpClient().Close(); // Accept the client connection and immediately close it.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜