namewchwch 2010年08月23日
raw 套接字的udp包
#include<winsock2.h>
#include<ws2tcpip.h>
#include<iostream>
#include<string>
#include"rawsock.h"
using namespace std;
unsigned short checksum(unsigned short *buff,int size)
{
unsigned long cksum = 0;
while(size>1)
{
cksum += *buff++;
size -= sizeof(unsigned short);
}
if(size)
{
cksum += *(unsigned char*)buff;
}
cksum = (cksum>>16) + (cksum&0xffff);
cksum += (cksum>>16);
return (unsigned short)(~cksum);

}
int main(void)
{
string ip;unsigned short port;
WSAData wsaData;
SOCKADDR_IN addr_in;
UDP_HEADER udp_head;
IP_HEADER ip_head;
PSD_HEADER psd_head;
char Buf[256] = {0};
BOOL flag ;
int rect;

if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
{
cerr<<"fail to find winsocket 2.1 or better"<<endl;
return 0;
}
SOCKET sockfd;
sockfd = WSASocket(AF_INET,SOCK_RAW,IPPROTO_RAW,0,0,WSA_FLAG_OVERLAPPED);
if(INVALID_SOCKET==sockfd)
{
cout<<"set socket fail"<<endl;
return 0;
}
flag = TRUE;
if(setsockopt(sockfd,IPPROTO_IP,IP_HDRINCL,(char*)&flag,sizeof(flag))==SOCKET_ERROR)
{
int k = GetLastError();
cout<<"setsockopt fail;"<<endl;
return 0;
}
int nTimeOver = 1000;
if(setsockopt(sockfd,SOL_SOCKET,SO_SNDTIMEO,(char*)&nTimeOver,sizeof(nTimeOver))==SOCKET_ERROR)
{
cout<<"set timeout item fail "<<endl;
return 0;
}
cin>>port;
addr_in.sin_family = AF_INET;
addr_in.sin_port = htons(port);
addr_in.sin_addr.S_un.S_addr = inet_addr("60.28.205.44");
ip_head.ver =(4<<4 | sizeof(ip_head)/sizeof(unsigned long));
ip_head.total_len = htons(sizeof(ip_head)+sizeof(udp_head));
ip_head.ident = 1;
ip_head.frag_and_flags = 0;
ip_head.ttl = 128;
ip_head.proc = IPPROTO_UDP;
ip_head.check_sum = 0;
ip_head.source_ip = inet_addr("1.0.0.12"); //假的ip
ip_head.dest_ip = inet_addr("192.168.1.12"); //目标ip

udp_head.sourceport = htons(port);
udp_head.sourceport = htons(2123);
udp_head.udp_len = htons(sizeof(udp_head));
udp_head.check_sum = 0;
psd_head.souraddr = ip_head.source_ip;
psd_head.destaddr = ip_head.dest_ip;
psd_head.mbz = 0;
psd_head.ptcl = IPPROTO_UDP;
psd_head.tcp_len = htons(sizeof(udp_head));
memcpy(Buf,&psd_head,sizeof(psd_head));
memcpy(Buf+sizeof(psd_head),&udp_head,sizeof(udp_head));
udp_head.check_sum = checksum((unsigned short*)Buf,sizeof(psd_head)+sizeof(udp_head));
memset(Buf+sizeof(ip_head)+sizeof(udp_head),0,sizeof(Buf));
memcpy(Buf,&ip_head,sizeof(ip_head));
memcpy(Buf,&udp_head,sizeof(udp_head));
ip_head.check_sum = checksum((unsigned short*)Buf,sizeof(ip_head)+sizeof(udp_head));
//strcpy(Buf+size);
rect = sendto(sockfd,Buf,sizeof(ip_head)+sizeof(udp_head),0,(struct sockaddr*)&addr_in,sizeof(addr_in));
if(SOCKET_ERROR==rect)
{
rect = WSAGetLastError(); //这里总是在返回错误10004
cout<<"sendto Error : "<<rect<<endl;
return 0;
}
closesocket(sockfd);
WSACleanup();
return 0;
}





注意了:我已经关闭了windows的防火墙和其他的防火墙软件。
...全文
7 点赞 收藏 1
写回复
1 条回复

还没有回复,快来抢沙发~

发动态
发帖子
网络编程
创建于2007-09-28

7878

社区成员

6.4w+

社区内容

VC/MFC 网络编程
社区公告
暂无公告