Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

c++ - Refusing connection from a host

I'm writing a simple tcp server application using sockets. As far as I know I can obtain the client's ip address and port after calling accept().

Now lets assume I have a banlist and I want to ban some ip addresses from my server. Is there a better way than accepting the connection and then dropping it?

Is there a way to get the client's ip and port before accepting the connection? If we have accept() why don't we have something like refuse()? Is there a way to refuse the connection or simply ignore connection attempt from a host?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The TCP implementation normally completes the TCP 3-way handshake before the user process even has access to the connection, and the accept() function merely gets the next connection off the queue. So it is too late to pretend that the server is down. This works the same way for regular TCP data; the TCP implementation does not wait for the application to actually recv() the data before a TCP ACK is sent. This keeps the other side from needlessly retransmitting packets that were received correctly, and allows the throughput to remain high, even when the application is bogged down with other things. In the case of new connections (SYN packets), this also allows the kernel to protect itself (and the application) from SYN flood attacks.

Although not portable, many platforms provide some sort of firewall capability that will allow filtering incoming connections based on IP address/port. However that is usually configured system-wide and not by an individual application.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...