当前位置:文档之家› 网络协议实验报告

网络协议实验报告

实验一:

unsigned short checkSum(char*pBuffer,int nLen)

{

unsigned short nWord;

unsigned int nSum=0;

int i;

for(i=0;i

{

nWord=((pBuffer[i]<<8)&0xFF00)+(pBuffer[i+1]&0xFF);

nSum=nSum+(unsigned int)nWord;

}

while(nSum>>16)

{

nSum=(nSum&0xFFFF)+(nSum>>16);

}

nSum=~nSum;

return((unsigned short)nSum);

}

int timeout=1000;

setsockopt(sock_raw,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,sizeof(timeout));

setsockopt(sock_raw,SOL_SOCKET,SO_SNDTIMEO,(char*)&timeout,sizeof(timeout)); ICMPheader*pIcmpHeader=(ICMPheader*)sendBuffer;

pIcmpHeader->byType=8;

pIcmpHeader->byCode=0;

pIcmpHeader->nId=(USHORT)::GetCurrentProcessId();

pIcmpHeader->nChecksum=0;

pIcmpHeader->nSequence=htons(nSeq++);

memset(sendBuffer+sizeof(ICMPheader),'*',32);

pIcmpHeader->nChecksum=htons(checkSum(sendBuffer,

sizeof(ICMPheader)+32));

int nRet=sendto(sock_raw,sendBuffer,sizeof(ICMPheader)+32,0, (SOCKADDR*)&dest_addr,sizeof(SOCKADDR_IN));

IPheader*ipHdr=(IPheader*)recvBuffer;

ICMPheader*icmpHdrRet=(ICMPheader*)(recvBuffer+sizeof(IPheader));

if(icmpHdrRet->byCode==0&&

icmpHdrRet->nId==pIcmpHeader->nId&&

icmpHdrRet->nSequence==pIcmpHeader->nSequence)

{

nPacketReceived++;

unsigned long dwRecvTime=::GetTickCount();

int nRoundTime=dwRecvTime-dwSendTime;

nTotalRoundTime+=nRoundTime;

if(nMinRoundTime==-1)

{

nMinRoundTime=nRoundTime;

nMaxRoundTime=nRoundTime;

}

if(nRoundTime

{

nMinRoundTime=nRoundTime;

}

if(nRoundTime>nMaxRoundTime)

{

nMaxRoundTime=nRoundTime;

}

cout<<"Reply from "<

if(nPacketReceived)

{

cout<<"\rApproximate round trip times in milli-seconds:"<

}

实验二:

//此函数获取本机DNS服务器地址(为点分十进制计法的字符串形式),并保存到dnsServer中,这里需要Iphlpapi.h和IPHLPAPI.LIB

void getDnsServer(char*dnsServer)

{

//获得需要的缓冲区大小

相关主题