傳送原始udp封包時:
1 以ipproto_udp 為協議型別建立乙個原始套接字,開啟原始套接字上的ip_hdrincl選項
2 構建udp封包,要先設定ip頭,設定udp頭,最後udp淨荷資料。
3 初始化完整的udp封包之後,呼叫sendto函式即可將他傳送。
計算udp封包校驗和的過程如下:
voidcomputeu***seudoheaderchecksum(
ipheader *piphdr,
udpheader *pudphdr,
char *payload,
intpayloadlen
)//計算這個校驗和,將結果填充到udp頭
pudphdr->checksum = checksum((ushort*)buff, chksumlen);
}
傳送原始udp封包的過程如下:
intmain()
;
//ip頭
ipheader *piphdr = (ipheader *)buff;
piphdr->iphverlen = (4
<<4 | (sizeof(ipheader)/sizeof
(ulong)));
piphdr->iplength = ::htons(sizeof(ipheader) + sizeof(udpheader) +nmsglen);
piphdr->ipttl = 128
; piphdr->ipprotocol =ipproto_udp;
piphdr->ipsource =::inet_addr(szsourceip);
piphdr->ipdestination =::inet_addr(szdestip);
piphdr->ipchecksum = checksum((ushort*)piphdr, sizeof
(ipheader));
//udp頭
udpheader *pudphdr = (udpheader *)&buff[sizeof
(ipheader)];
pudphdr->sourceport = htons(8888
); pudphdr->destinationport =htons(ndestport);
pudphdr->len = htons(sizeof(udpheader) +nmsglen);
pudphdr->checksum = 0
;
char *pdata = &buff[sizeof(ipheader) + sizeof
(udpheader)];
memcpy(pdata, szmsg, nmsglen);
computeu***seudoheaderchecksum(piphdr, pudphdr, pdata, nmsglen);
//設定目的位址
sockaddr_in destaddr = ;
destaddr.sin_family =af_inet;
destaddr.sin_port =htons(ndestport);
destaddr.sin_addr.s_un.s_addr =::inet_addr(szdestip);
//傳送原始udp封包
intnret;
for(int i=0; i<5; i++)
else
}::closesocket(sraw);
getchar();
return0;
}
posted @
2012-10-21 21:57
xingoo 閱讀(
...)
編輯收藏
UDP 傳送廣播
服務端 using system using system.collections.generic using system.componentmodel using system.data using system.drawing using system.linq using system.te...
QT入門 udp傳送
intmain int argc char argv 在demodialog.h中定義udp傳送變數 udp傳送變數 qudpsocket udp socket tx qudpsocket udp socket rx qhostaddress ip tx 要傳送的位址 intport tx 要傳送的...
udp傳送廣播訊息
import socket if name main 建立udpsocket udp socket socket.socket socket.af inet,socket.sock dgram 設定socket選項,開啟傳送廣播訊息的功能 1.sol socket 當前socket 2.so bro...