当前位置: 技术问答>linux和unix
linux下构造TCP数据包的问题
来源: 互联网 发布时间:2016-08-23
本文导语: #include #include #include #include #include //伪头部 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) { in...
#include
#include
#include
#include
#include
//伪头部
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)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, '', 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