如何用原始套接字进行网络通讯

王朝vc·作者佚名  2006-01-08
宽屏版  字体: |||超大  

下面是我写的一个用原始套接字进行网络通讯的代码(只有关键的部分),原始套接字很强大,它可以自定义协议和传输机制,它的最多的用处当然是黑客了,可以进行IP攻击,但我还没学到那么深:),下面是代码了:

typedef struct ip_hdr

{

unsigned char ip_verlen;

unsigned char ip_tos;

unsigned short ip_totallength;

unsigned short ip_id;

unsigned short ip_offset;

unsigned char ip_ttl;

unsigned char ip_protocol;

unsigned short ip_checksum;

unsigned int ip_srcaddr;

unsigned int ip_destaddr;

}IP_HDR;

typedef struct udp_hdr

{

unsigned short src_portno;

unsigned short dst_portno;

unsigned short udp_length;

unsigned short udp_checksum;

}UDP_HDR;

void CNettestDlg::OnStart()

{

WSADATA wsa;

SOCKET s;

CString str;

struct sockaddr_in remote;

IP_HDR iphdr; file://Ip header

UDP_HDR udphdr; file://UDP header

int ret;

unsigned short itotalsize,

iudpsize,

iIPversion,

iIPsize;

char buf[100];

char *ptr;

BOOL bopt=TRUE;

GetDlgItemText(IDC_STR,str); file://这是得到我的编辑控件中的字串

strcpy(buf,str);

if(WSAStartup(MAKEWORD(2,2),&wsa)!=0)

s=WSASocket(AF_INET,SOCK_RAW,IPPROTO_UDP,NULL,0,0);

ret=setsockopt(s,IPPROTO_IP,IP_HDRINCL,(char *)&bopt,sizeof(bopt));

itotalsize=sizeof(iphdr)+sizeof(udphdr)+strlen(buf);

iIPversion=4;

iIPsize=sizeof(iphdr)/sizeof(unsigned long);

file://初始化IP头

iphdr.ip_verlen=(iIPversion<<4)|iIPsize;

iphdr.ip_tos=0; file://IP type of serverce

iphdr.ip_totallength=htons(itotalsize); file://total packet len

iphdr.ip_id=0;

iphdr.ip_offset=0;

iphdr.ip_ttl=128; file://time of live

iphdr.ip_protocol=0x11; file://udp协议

iphdr.ip_checksum=0; file://IP校验和

iphdr.ip_srcaddr= inet_addr("127.0.0.1"); file://源IP地址

iphdr.ip_destaddr=inet_addr("127.0.0.1"); file://目标IP地址

iudpsize=sizeof(udphdr)+strlen(buf);

file://初始化UDP头

udphdr.dst_portno=htons(1999); file://目标端口

udphdr.src_portno=htons(1999); file://源端口

udphdr.udp_checksum=0;

udphdr.udp_length=htons(iudpsize);

file://构建UDP包

ZeroMemory(buf,100);

ptr=buf;

memcpy(ptr,&iphdr,sizeof(iphdr));

ptr+=sizeof(iphdr);

memcpy(ptr,&udphdr,sizeof(udphdr));

ptr+=sizeof(udphdr);

memcpy(ptr,str,strlen(str));

remote.sin_family=AF_INET;

remote.sin_port=htons(1990);

remote.sin_addr.s_addr=inet_addr("127.0.0.1");

sendto(s,buf,itotalsize,0,(SOCKADDR *)&remote,sizeof(remote));

closesocket(s);

WSACleanup();

}

至于接收端那边,就是很简单的recvfrom()就行了.

大家可能看到了setsockopt(s,IPPROTO_IP,IP_HDRINCL,(char *)&bopt,sizeof(bopt))这个涵数里有个IP_HDRINCL的选项,这个选项代表你可以自己定义协议头,很可惜因为这个标志限制了只能在win2000中编程,而98大概就不行了,不过我也没有试过,而s=WSASocket(AF_INET,SOCK_RAW,IPPROTO_UDP,NULL,0,0)这个涵数中的SOCK_RAW就是原始套接字的标志,在接收端收到的字串里就会是你想传过来的字串,而用memcpy()的iphdr,和udphdr却不见了.

所以请这方面的高手告诉我,为什么接收到的字串里会看不到iphdr,udphdr字段

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有