原始套接字编程(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.

参考:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

callinglove

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值