原始套接字编程(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)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: window连接不上ssdb的问题
- 下一篇: javaWeb回忆思维导图