Linux TCP服务器:在接受连接之前读取客户端的IP地址

编程入门 行业动态 更新时间:2024-10-25 12:23:38
本文介绍了Linux TCP服务器:在接受连接之前读取客户端的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

相关: C ++ Winsock API如何在接受连接之前获取连接的客户端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地址

本文发布于:2023-10-15 00:52:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492753.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   地址   服务器   在接受   Linux

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!