Linux TCP服务器:在接受连接之前读取客户端的IP地址 [英] Linux TCP server: reading client's IP address before accepting connection

查看:93
本文介绍了Linux TCP服务器:在接受连接之前读取客户端的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相关:当您运行TCP服务器(使用Berkeley Socket API用C语言编写)时,是否可以在实际接受连接之前读取客户端的IP地址/端口?

Hi, when you are running a TCP server (written in C, using the Berkeley Socket API) is it possible to read a client's IP address/port before actually accepting the connection?

据我所知,您必须 接受 首先连接,然后 shutdown 之后,如果您由于其IP地址不想与给定的客户端通信,则直接关闭它.

As far as I know you have to accept the connection first and shutdown it directly thereafter, if you don't want to communicate with a given client because of its IP address.

伪代码(我正在寻找 peek refuse 方法):

Pseudo-code (I am looking for the peek and refuse method):

 int serverfd = listen(...);
 for(;;) {
     struct sockaddr_in clientAddr;
     peek(serverfd, &clientAddr, sizeof(clientAddr));
     if(isLegit(&clientAddr)) {
         int clientfd = accept(serverfd, &clientAddr, sizeof(clientAddr));
         handleClient(clientfd);
     } else {
         refuse(serverfd, &clientAddr, sizeof(clientAddr));
     }
 }

推荐答案

我认为您的尝试是防止与特定IP匹配的TCP协商的发生.据我所知,这在套接字层是不可能的.TCP协商将发生,并且到您接受套接字时,该协商已经发生.

I think what your trying to do is prevent the TCP negotiation from occurring if it matches a specific IP. As far as I know, that is not possible at the sockets layer. The TCP negotiation will occur, and by the time you come to accept the socket, the negotiation has already happened.

从技术上讲,您可能会以某种方式偷看该状态信息,但是,它并没有按照您的预期去做.接受套接字的是已经完成工作的内核和想要读取数据的程序之间的接口.最简单的方法是接受套接字,然后在不需要时引导它.

Technically it is possible that you could somehow peek at that state information, but, it wouldn't be doing what you expect it to do. Accepting the socket is the interface between the kernel, which already did the work, and your program which would like to read the data. The easiest thing to do is accept the socket, and boot it if you don't want it.

如果首先要防止TCP协商发生,则需要使用iptables.

If you want to prevent the TCP negotiation from occurring in the first place, you need to use iptables.

这篇关于Linux TCP服务器:在接受连接之前读取客户端的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆