日期:2014-05-16  浏览次数:20760 次

求助:多线程中的原始套接字问题
在linux下用原始套接字写了个SYN扫描。
线程函数:
{
  创建原始套接字;
  构造数据包;
  发送数据包;
  接收数据包;  
}
线程函数没有问题,单一线程可以正确扫描。多线程时候问题就出在接收数据包。
例如:
thread 1:scan 20 port,一直等待;
thread 2:scan 21 port,recv 20 port;
……
也就是虽然我每个线程创建了不同套接口,但是貌似有数据来的时候,会全部留到所创建套接口的缓冲区中,怎么解决?
线程怎么区分数据包,怎么样才能使得scan 20 port的,只等待20端口返回的TCP数据包?


顺便问问,TCP套接口可以靠4源组标识,那不同原始套接口怎么区分?

------解决方案--------------------
When the kernel has an IP datagram to pass to the raw sockets, all raw sockets for all processes are examined, looking for all matching sockets. A copy of the IP datagram is delivered to each matching socket. The following tests are performed for each raw socket and only if all three tests are true is the datagram delivered to the socket:

If a nonzero protocol is specified when the raw socket is created (the third argument to socket), then the received datagram's protocol field must match this value or the datagram is not delivered to this socket.

If a local IP address is bound to the raw socket by bind, then the destination IP address of the received datagram must match this bound address or the datagram is not delivered to this socket.

If a foreign IP address was specified for the raw socket by connect, then the source IP address of the received datagram must match this connected address or the datagram is not delivered to this socket.

Notice that if a raw socket is created with a protocol of 0, and neither bind nor connect is called, then that socket receives a copy of every raw datagram the kernel passes to raw sockets.

------解决方案--------------------
不用每次都创建套接字的,只要每次有一个客户端和你建立连接,就创建一个线程,这样以后收到的数据就是对应的客户端的数据