伪造IP发送数据(UDP)

 

#include 
#include 
#include 
#include 
#include 
#include "protoinfo.h"
#pragma comment (lib,"ws2_32.lib")
using namespace std;
#define SOURCEPORT 65432
#define DESTPORT   65431
USHORT CheckSum(PUSHORT buf,int size)
{
  ULONG  sum=0;
  while(size>1)
  {
    sum+=*buf;
	buf++;
	size-=2;
  }
  if(size)
	  sum+=*(char *)buf;
  sum=(sum>>16)+(sum&0xffff);
  sum+=sum>>16;
  return (~sum);
 
}
 
int main()
{
	char szDestIp[]="119.75.218.70";
    char szSourceIp[]="192.168.1.102";
	char szMsg[]="Hello ,Can you receive my message!";
	int  msgLen=sizeof(szMsg);
	int ret;
	WSADATA wsaData;
	if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
	{
	  return -1;
	}
	SOCKET sockRaw;
	sockRaw=socket(AF_INET,SOCK_RAW,IPPROTO_RAW);
	int h_incl=1;
	ret=setsockopt(sockRaw,IPPROTO_IP,IP_HDRINCL,(char *)&h_incl,sizeof(h_incl));
	//创建并填充IP首部
	char buf[1024]={0};
	IPHeader  *pIpHead=(IPHeader *)buf;
	pIpHead->iphVerLen=4<<4|(sizeof(IPHeader)/sizeof(ULONG));
	pIpHead->ipLength=htons(sizeof(IPHeader)+sizeof(UDPHeader));
	pIpHead->ipTTL=128;
	pIpHead->ipProtocol=IPPROTO_UDP;
	pIpHead->ipSource=inet_addr(szSourceIp);
	pIpHead->ipDestination=inet_addr(szDestIp);
	pIpHead->ipChecksum=CheckSum((PUSHORT)pIpHead,sizeof(IPHeader));//IP 首部的校验和只需要校验IP首部
    //填充UDP首部
	UDPHeader *pUdpHeader=(UDPHeader *)&buf[sizeof(IPHeader)];
	pUdpHeader->sourcePort=htons(SOURCEPORT);
	pUdpHeader->destinationPort=htons(DESTPORT);
	pUdpHeader->len=htons(sizeof(UDPHeader)+sizeof(szMsg));
	pUdpHeader->checksum=0;
	//填充UDP数据
	char *pData;
	pData=&buf[sizeof(IPHeader)+sizeof(UDPHeader)];
	memcpy(pData,szMsg,sizeof(szMsg));
	//计算UDP校验和
	UDPFakeHead mUDPFakeHead;
	mUDPFakeHead.sourceIp=pIpHead->ipSource;
	mUDPFakeHead.destIp=pIpHead->ipDestination;
	mUDPFakeHead.filling=0;
	mUDPFakeHead.protocalType=IPPROTO_UDP;
	mUDPFakeHead.UDPLength=htons(sizeof(UDPHeader)+sizeof(szMsg));
 
	//设置szBuffer目的是计算UDP校验和
	char szBuffer[1024];
	memcpy(szBuffer,&mUDPFakeHead,sizeof(UDPFakeHead));
	memcpy(&szBuffer[sizeof(UDPFakeHead)],pUdpHeader,sizeof(UDPHeader));
	memcpy(&szBuffer[sizeof(UDPFakeHead)+sizeof(UDPHeader)],szMsg,sizeof(szMsg));
	pUdpHeader->checksum=CheckSum((PUSHORT)szBuffer,sizeof(UDPFakeHead)+sizeof(UDPHeader)+sizeof(szMsg));
	//设置目的地址
	sockaddr_in addrDest;
	addrDest.sin_family=AF_INET;
	addrDest.sin_addr.S_un.S_addr=inet_addr(szDestIp);
	addrDest.sin_port=htons(DESTPORT);
	for(int i=0;i<5;i++)
	{
		ret=sendto(sockRaw,buf,sizeof(UDPFakeHead)+sizeof(UDPHeader)+sizeof(szMsg),0,(sockaddr *)&addrDest,sizeof(addrDest));
		if(ret==SOCKET_ERROR)
		{
		  cout<<"发送失败"<

 

你可能感兴趣的:(windows编程)