原始套接字编程(1)

Linux下原始套接字的原理

创建原始套接字:
socket(AF_NET, SOCK_RAW, protocol);

1. 参数protocol用来致命所接收的协议包,如果是像IPPROTO_TCP(6)这种非0、非255的协议,能接收ip头为protocol域的数据包,包括IP头,协议头以及数据;发送数据时,默认只需构建protocol协议头及数据,不需构建IP头。可以通过设置原始套接字的IP_HDRINCL属性,使用户自己构建IP头。
setsockopt (rawsock, IP, IP_HDRINCL, “1”, sizeof (“1”));
2. 如果protocol为IPPROTO_RAW,创建的原始套接字只能用来发送IP数据包,且默认开启IP_HDRINCL属性,需要用户自己构建IP包头,计算校验和。
3. 对于protocol为IPPROTO_IP的原始套接字,可以接收任何的IP数据包。其中的校验和验证和协议分析由程序自己完成。
4. 若要监测所有输入与输出的数据包,而且不仅限制于IP包(tcp/udp/icmp),监测 arp/rarp包,以及以太网头部,需要通过以下语句建立原始套接字:
sock_raw = socket( AF_PACKET , SOCK_RAW , htons(ETH_P_ALL)) ;

原始套接字在windows下的局限

Limitations on Raw Sockets
On Windows 7, Windows Vista, Windows XP with Service Pack 2 (SP2), and Windows XP with Service Pack 3 (SP3), the ability to send traffic over raw sockets has been restricted in several ways:

  • TCP data cannot be sent over raw sockets.
  • UDP datagrams with an invalid source address cannot be sent over raw sockets. The IP source address for any outgoing UDP datagram must exist on a network interface or the datagram is dropped. This change was made to limit the ability of malicious code to create distributed denial-of-service attacks and limits the ability to send spoofed packets (TCP/IP packets with a forged source IP address).
  • A call to the bind function with a raw socket for the IPPROTO_TCP protocol is not allowed.

Note The bind function with a raw socket is allowed for other protocols (IPPROTO_IP, IPPROTO_UDP, or IPPROTO_SCTP, for example).

These above restrictions do not apply to Windows Server 2008 R2, Windows Server 2008 , Windows Server 2003, or to versions of the operating system earlier than Windows XP with SP2.

参考:

  • 浅谈原始套接字 SOCK_RAW 的内幕及其应用
  • http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=876233
  • Linux网络编程:原始套接字的魔力
  • raw socket遇上windows

你可能感兴趣的:(原始套接字编程(1))