日期:2014-05-16 浏览次数:20738 次
#include <sys/socket.h> #include <sys/types.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <string.h> //伪头部 struct psd { struct in_addr src; struct in_addr dst; char zero; char p; unsigned short len; }; //校验函数 unsigned short chksum(unsigned char *data, int len) { int sum=0; int odd = len & 0x01; unsigned short *value = (unsigned short*)data; while( len & 0xfffe) { sum += *(unsigned short*)data; data += 2; len -=2; } if(odd) { unsigned short tmp = ((*data)<<8)&0xff00; sum += tmp; } sum = (sum >>16) + (sum & 0xffff); sum += (sum >>16) ; return ~sum; } //发送包 void sendtcp() { int ret =0; char buffer[1024]; struct psd * psd = (struct psd *)buffer; //伪头部 = 12字节 struct tcphdr *tcp = (struct tcphdr *)(buffer+12); struct sockaddr_in addr; int s = socket(AF_INET, SOCK_RAW, 6); memset(buffer, '\0', 1024); addr.sin_family = AF_INET; addr.sin_port = htons(80); addr.sin_addr.s_addr = inet_addr("192.168.205.64"); //目标地址 //伪头部 psd->src.s_addr = inet_addr("192.168.205.113"); //源地址 psd->dst.s_addr = inet_addr("192.168.205.64"); psd->p = 6; psd->zero = 0; psd->len = htons(8); //TCP数据包 = 64字节 tcp->source = htons(9090); tcp->dest = htons(80); tcp->seq = htons(1234); tcp->doff = 5; //TCP头部 = 5*4 = 20字节 tcp->syn = 1; tcp->window = htons(1024); tcp->check = htons(chksum(buffer, 76)); //伪头部 + TCP数据包 = 76字节 //TCP数据包 = 64字节 ret = sendto(s, (char*)tcp, 64, 0, (struct sockaddr*)&addr, sizeof(addr)); if(ret < 0) { perror("sendto"); } printf("send over, send %d bytes\n", ret); } int main() { sendtcp(); return 0; }