IPman中的C代码,参考一下吧:
WORD CheckSum(WORD *addr,WORD len)
{
DWORD lSum;
WORD wOddByte;
WORD wAnswer;
lSum=0l;
while(len>1) {
lSum+= *addr++;
len-=2;
}
if(len==1) {
wOddByte=0;
*((unsigned char*)&wOddByte)=*(unsigned char*)addr;
lSum+=wOddByte;
}
lSum=(lSum>>16)+(lSum&0xffff);
lSum+=(lSum>>16);
wAnswer=(unsigned int)~lSum;
return wAnswer;
}
...
WORD SendTCPPacket(HANDLE hVxD,
struct EtherAddr *psourether,
struct EtherAddr *pdestether,
struct IPAddr *psourip,
struct IPAddr *pdestip,
WORD sourport,
WORD destport,
WORD flag,
DWORD seqno,
DWORD ackno,
char *pbuf,
WORD len)
{
char Buffer[BUFFER_SIZE];
char HelpBuffer[BUFFER_SIZE];
char *pdata;
struct EtherPacketHead *pEtherHead;
struct IPPacketHead *pIPHead;
struct TCPPacketHead *pTCPHead,*pHelpTCPHead;
struct PseudoHead *pPseudoHead;
static WORD id=0;
WORD wlen;
id++;
memset(Buffer,0,BUFFER_SIZE);
pEtherHead=(struct EtherPacketHead *)Buffer;
pIPHead=(struct IPPacketHead *)(Buffer+ETHER_HEAD_LEN);
pTCPHead=(struct TCPPacketHead *)(Buffer+ETHER_HEAD_LEN+IP_HEAD_BYTE_LEN);
pPseudoHead=(struct PseudoHead *)HelpBuffer;
pHelpTCPHead=(struct TCPPacketHead *)(HelpBuffer+PSEUDO_HEAD_LEN);
pdata=(char *)(Buffer+ETHER_HEAD_LEN+IP_HEAD_BYTE_LEN+TCP_HEAD_BYTE_LEN);
/* Set ether head */
memcpy((void *)&pEtherHead->SourEther,(void *)psourether,6);
memcpy((void *)&pEtherHead->DestEther,(void *)pdestether,6);
pEtherHead->ServType=swaps(ETHER_PROTO_IP);
/* Set IP head */
memcpy((void *)&pIPHead->SourIP,(void *)psourip,4);
memcpy((void *)&pIPHead->DestIP,(void *)pdestip,4);
pIPHead->VerHLen=(IP_VER<<4)|IP_HEAD_LEN;
pIPHead->Type=IP_SERV_TYPE;
wlen=len+TCP_HEAD_BYTE_LEN+IP_HEAD_BYTE_LEN;
pIPHead->TtlLen=swaps(wlen);
pIPHead->Id=swaps(id);
pIPHead->FlgOff=0;
pIPHead->TTL=69;
pIPHead->Proto=IP_PROTO_TCP;
pIPHead->ChkSum=0;
pIPHead->ChkSum=CheckSum((WORD *)pIPHead,IP_HEAD_BYTE_LEN);
/* Set TCP head */
pTCPHead->SourPort=swaps(sourport);
pTCPHead->DestPort=swaps(destport);
pTCPHead->SeqNo=swapl(seqno);
pTCPHead->AckNo=swapl(ackno);
pTCPHead->HLen=TCP_HEAD_LEN<<4;
pTCPHead->Flag=flag;
pTCPHead->WndSize=swaps(8192);
pTCPHead->ChkSum=0;
pTCPHead->UrgPtr=0;
/* Set TCP data */
memcpy((void *)pdata,(void *)pbuf,len);
/* Calculate TCP checksum */
memcpy((void *)&pPseudoHead->SourIP,(void *)psourip,4);
memcpy((void *)&pPseudoHead->DestIP,(void *)pdestip,4);
pPseudoHead->Pad=0;
pPseudoHead->Proto=IP_PROTO_TCP;
wlen=len+TCP_HEAD_BYTE_LEN;
pPseudoHead->Len=swaps(wlen);
memcpy((void *)pHelpTCPHead,(void *)pTCPHead,wlen);
wlen=len+TCP_HEAD_BYTE_LEN+PSEUDO_HEAD_LEN;
pTCPHead->ChkSum=CheckSum((WORD *)HelpBuffer,wlen);
wlen=len+TCP_HEAD_BYTE_LEN+IP_HEAD_BYTE_LEN+ETHER_HEAD_LEN;
if(SendPacket(hVxD,Buffer,wlen)==SYSERR) {
fprintf(stderr,"Can not send TCP packet./n");
return SYSERR;
}
return OK;
}