在利用Raw Socket发送报文时,报文的IP头、TCP头、UDP头等需要程序员亲自赋值,从而达到极大的灵活性。下面的程序利用Raw Socket发送TCP报文,并完全手工建立报头:
int sendTcp(unsigned short desPort, unsigned long desIP) { WSADATA WSAData; SOCKET sock; SOCKADDR_IN addr_in; IPHEADER ipHeader; TCPHEADER tcpHeader; PSDHEADER psdHeader;
char szSendBuf[MAX_LEN] = { 0 }; BOOL flag; int rect, nTimeOver;
if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0) { printf("WSAStartup Error!\n"); return false; }
if ((sock = WSASocket(AF_INET, SOCK_RAW, IPPROTO_RAW, NULL, 0, WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET) { printf("Socket Setup Error!\n"); return false; } flag = true; if (setsockopt(sock, IPPROTO_IP, IP_HDRINCL, (char*) &flag, sizeof(flag)) ==SOCKET_ERROR) { printf("setsockopt IP_HDRINCL error!\n"); return false; }
nTimeOver = 1000; if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char*) &nTimeOver, sizeof (nTimeOver)) == SOCKET_ERROR) { printf("setsockopt SO_SNDTIMEO error!\n"); return false; } addr_in.sin_family = AF_INET; addr_in.sin_port = htons(desPort); addr_in.sin_addr.S_un.S_addr = inet_addr(desIP);
//填充IP报头 ipHeader.h_verlen = (4 << 4 sizeof(ipHeader) / sizeof(unsigned long)); // ipHeader.tos=0; ipHeader.total_len = htons(sizeof(ipHeader) + sizeof(tcpHeader)); ipHeader.ident = 1; ipHeader.frag_and_flags = 0; ipHeader.ttl = 128; ipHeader.proto = IPPROTO_TCP; ipHeader.checksum = 0; ipHeader.sourceIP = inet_addr("localhost"); ipHeader.destIP = desIP;
//填充TCP报头 tcpHeader.th_dport = htons(desPort); tcpHeader.th_sport = htons(SOURCE_PORT); //源端口号 tcpHeader.th_seq = htonl(0x12345678); tcpHeader.th_ack = 0; tcpHeader.th_lenres = (sizeof(tcpHeader) / 4 << 4 0); tcpHeader.th_flag = 2; //标志位探测,2是SYN tcpHeader.th_win = htons(512); tcpHeader.th_urp = 0; tcpHeader.th_sum = 0;
psdHeader.saddr = ipHeader.sourceIP; psdHeader.daddr = ipHeader.destIP; psdHeader.mbz = 0; psdHeader.ptcl = IPPROTO_TCP; psdHeader.tcpl = htons(sizeof(tcpHeader));
//计算校验和 memcpy(szSendBuf, &psdHeader, sizeof(psdHeader)); memcpy(szSendBuf + sizeof(psdHeader), &tcpHeader, sizeof(tcpHeader)); tcpHeader.th_sum = checksum((unsigned short*)szSendBuf, sizeof(psdHeader) + sizeof (tcpHeader)); memcpy(szSendBuf, &ipHeader, sizeof(ipHeader));
上一篇:黑客之旅――原始套接字透析之前言
下一篇:原始套接字透析之ICMP拒绝服务攻击
|