场景描述:测试RTP数据包的丢失个数,应用于windows平台
// MultiCastRecv.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib,"ws2_32.lib")
#include<windows.h>
#include <iostream>
using namespace std;
int InitSockLib()
{
WORD wVersionRequested;
WSADATA wsaData;
int nret;
wVersionRequested = MAKEWORD( 1, 1 );
nret = WSAStartup( wVersionRequested, &wsaData );
if ( nret != 0 ) {
return -1 ;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );
return -2;
}
return 0;
}
int CreateMultiSock(char* pszMultiAddr,char* pszLocalIP,short sPort)
{
int nret;
if(InitSockLib()!=0)
{
cout<<"Can not Init Socket Lib"<<endl;
return -1;
}
else
{
cout<<"Init Socket Lib successfully"<<endl;
}
struct ip_mreq SMreq;
SOCKET SockServer=socket(AF_INET,SOCK_DGRAM,0);
if(SockServer<0)
{
cout<<"Can not create socket"<<endl;
return -2;
}
else
{
cout<<"create socket successfully"<<endl;
}
SOCKADDR_IN addrServer;
short sRecvPort=16572;
int addrLen=sizeof(struct sockaddr_in);
memset(&addrServer,0,sizeof(struct sockaddr_in));
addrServer.sin_family=AF_INET;
addrServer.sin_port=htons(sPort);
addrServer.sin_addr.S_un.S_addr=inet_addr(pszLocalIP);
if(bind(SockServer,(struct sockaddr*)&addrServer,sizeof(struct sockaddr_in))<0)
{
printf("can not bind:%d,%d\n",WSAGetLastError(),sRecvPort);
return -6;
}
else
{
cout<<"bind successfully"<<endl;
}
memset(&SMreq,0,sizeof(SMreq));
nret = inet_pton(AF_INET,pszMultiAddr,&SMreq.imr_multiaddr.s_addr);
if ( nret != 1 )
{
return -3;
}
SMreq.imr_interface.s_addr= htonl(INADDR_ANY);//double interface need to modify
socklen_t ireuse=0;
nret = setsockopt(SockServer,SOL_SOCKET,SO_REUSEADDR,(char*)&ireuse,sizeof(ireuse));
if ( nret == -1)
{
cout<<"can not set reuse bindaddr"<<endl;
return -4;
}
nret = setsockopt(SockServer,IPPROTO_IP,IP_ADD_MEMBERSHIP,(char*)&SMreq,sizeof(SMreq));
if ( nret == -1)
{
return -5;
}
int nRecvLen=-1;
char szRecvBuf[1500]={0};
unsigned int nRTPLastSeq=0;
unsigned int nRTPNowSeq=0;
int nLostPackCount=0;
while(1)
{
nRecvLen=recvfrom(SockServer,szRecvBuf,1500,0,(struct sockaddr*)&addrServer,&addrLen);
nRTPNowSeq=szRecvBuf[2]%(0x100);
nRTPNowSeq=(nRTPNowSeq*(0x100))+szRecvBuf[3];
nLostPackCount=nRTPNowSeq-nRTPLastSeq;
if(nLostPackCount!=1)
{
cout<<"Lost Pack count:"<<nLostPackCount<<",Now Recv Pack Seq:"<<nRTPNowSeq<<",The Last Seq:"<<nRTPLastSeq<<endl;
}
nRTPLastSeq=nRTPNowSeq;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char szMultiIP[32]={0};
char szLocalIP[32]={0};
short sPort=0;
cout<<"Please input MultiIP:like:224.1.1.6"<<endl;
cin>>szMultiIP;
cout<<"Please input LocalIP:like:192.168.40.31"<<endl;
cin>>szLocalIP;
cout<<"Please input MultiAddr Port,which is from MultAddr"<<endl;
cin>>sPort;
CreateMultiSock(szMultiIP,szLocalIP,sPort);
return 0;
}
时间: 2024-10-01 05:19:17