当前位置: 首页>>代码示例>>C++>>正文


C++ Packet类代码示例

本文整理汇总了C++中Packet的典型用法代码示例。如果您正苦于以下问题:C++ Packet类的具体用法?C++ Packet怎么用?C++ Packet使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Packet类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: clear_if

Packet FormatContext::readPacket(OptionalErrorCode ec)
{
    clear_if(ec);

    if (!m_raw)
    {
        throws_if(ec, Errors::Unallocated);
        return Packet();
    }

    if (!m_streamsInfoFound)
    {
        fflog(AV_LOG_ERROR, "Streams does not found. Try call findStreamInfo()\n");
        throws_if(ec, Errors::FormatNoStreams);
        return Packet();
    }

    Packet packet;

    int sts = 0;
    int tries = 0;
    const int retryCount = 5;
    do
    {
        resetSocketAccess();
        sts = av_read_frame(m_raw, packet.raw());
        ++tries;
    }
    while (sts == AVERROR(EAGAIN) && (retryCount < 0 || tries <= retryCount));

    // End of file
    if (sts == AVERROR_EOF /*|| avio_feof(m_raw->pb)*/) {
        auto ec = std::error_code(sts, ffmpeg_category());
        fflog(AV_LOG_DEBUG,
              "EOF reaches, error=%d, %s, isNull: %d, stream_index: %d, payload: %p\n",
              sts,
              ec.message().c_str(),
              packet.isNull(),
              packet.streamIndex(),
              packet.data());
        av_pkt_dump_log2(m_raw, AV_LOG_DEBUG, packet.raw(), 0, m_raw->streams[packet.streamIndex()]);
        if (packet)
            sts = 0; // not an error
        else
            return packet;
    }

    if (sts == 0)
    {
        auto pberr = m_raw->pb ? m_raw->pb->error : 0;
        if (pberr)
        {
            // TODO: need verification
            throws_if(ec, pberr, ffmpeg_category());
            return packet;
        }
    }
    else
    {
        throws_if(ec, sts, ffmpeg_category());
        return packet;
    }

    if (packet.streamIndex() >= 0)
    {
        if ((size_t)packet.streamIndex() > streamsCount())
        {
            throws_if(ec, Errors::FormatInvalidStreamIndex);
            return packet;
        }

        packet.setTimeBase(m_raw->streams[packet.streamIndex()]->time_base);

        if (m_substractStartTime) {
            const auto startTs = stream(packet.streamIndex()).startTime();
            if (startTs.isValid()) {
                if (packet.pts().isValid())
                    packet.setPts(packet.pts() - startTs);
                if (packet.dts().isValid())
                    packet.setDts(packet.pts() - startTs);
            }
        }
    }

    packet.setComplete(true);

    return packet;
}
开发者ID:wlanjie,项目名称:AndroidFFmpeg,代码行数:88,代码来源:formatcontext.cpp

示例2: AckSceneExit

	AckSceneExit(Packet packet)
	{
		m_uid = packet.ReadU32();
	}
开发者ID:mirahs,项目名称:xxtools,代码行数:4,代码来源:AckSceneExit.cpp

示例3: main

int main(int argc, char* argv[]) {

    //parse args
    if (argc != 5) {
        std::cout << "This program requires 4 arguments in the following format!" << std::endl;
        std::cout << "sender <host address of emulator> <udp port number of emulator in FWD direction>" << "\n"
                  << "<udp port number of sender to receive acks> <fileName>" << std::endl;
        std::cout << "Example: sender 192.168.89.78 49998 11234 test.txt" << std::endl;
        return 1;
    }


    const char* ipAddr = argv[1];
    if (0 == strcmp(ipAddr, "localhost")) {
        ipAddr = "127.0.0.1";
    }

    unsigned long remoteIp = inet_addr(ipAddr);
    int remotePort = atoi(argv[2]);
    int senderPort = atoi(argv[3]);
    const char* fileName = argv[4];

    int totalPackets = 0;
    int totalBytes = 0;

    int sentPackets = 0;
    int sentBytes = 0;

    int seqNum = 0;
    signal(SIGALRM, signal_alarm_handler);
    bool timer_on = false;
    list<Packet *> packetsToSend;
    list<Packet *> packetsSent;

    //Open the file and prepare the packets for transmission
    ifstream transferFile(fileName);
    ofstream seqLog(seqFile);
    ofstream ackLog(ackFile);

    if (!(seqLog.is_open() && ackLog.is_open())) {
        return 1;
    }

    if (transferFile.is_open()) {
        char buffer[Packet::MAX_DATA_LENGTH];

        while(false == transferFile.eof()) {
            transferFile.read(buffer, Packet::MAX_DATA_LENGTH);
            Packet* packet = Packet::createPacket(seqNum, transferFile.gcount(), buffer);
            packetsToSend.insert(packetsToSend.end(), packet);

            LOG("Inserted packet %i in the queue\n", totalPackets);

            seqNum++;
            seqNum %= Packet::MAX_SEQ_NUMBER;
            totalPackets++;
            totalBytes += packet->getLength();
        }
    } else {
        LOG("The input file was not found..\n");
        return 1;
    }

    transferFile.close();

    //Add EOT packet
    Packet *eotPacket = Packet::createEOT(seqNum);
    packetsToSend.insert(packetsToSend.end(), eotPacket);
    totalPackets++;

    LOG("Packets ready for transmission: %i\n", totalPackets);
    LOG("Total data to be sent: %i\n", totalBytes);

    //open a udp socket and listen for str
    UDPSocket udpSocket;
    int ret = udpSocket.open(senderPort);
    ASSERT(ret == 0);
    LOG("Sender is transmitting & receiving on UDP Port %i\n", senderPort);

    /**
    * Core Logic
    * The sender can be in three states
    * 1. SEND_DATA : Sends a packet as long as data is available and window size is permitted
    * 2. RECV_ACK : Receives an acknowledgement for a previously sent data
    * 3. RESEND_DATA: If an ACK is not received for a previously sent data within timer, resend the data
    */
    while ((packetsToSend.size() > 0) || (packetsSent.size() > 0)) {
        if (udpSocket.hasData()) {
            g_state = SENDER_RECV_ACK;
        }

        switch(g_state)
        {
        /**
        * Within the WINDOW_SIZE, if data is available, send it.
        * Remove it from packetsToSend, and add it to packetsSent
        * If timer is off, turn it on.
        */
        case SENDER_SEND_DATA: {
            if (packetsSent.size() < WINDOW_SIZE && packetsToSend.size() > 0) {
//.........这里部分代码省略.........
开发者ID:nickbodd,项目名称:UWcs456Networking,代码行数:101,代码来源:original_sender.cpp

示例4: main

/**
 * @param argv[1] receiving port number
 * 			argv[2] destination address
 * 			argv[3] destination port number
 * 			argv[4] filename to save
 */
int main(int argc, const char * argv[])
{

	int state = WAITING_STATE;

try {
	  ofstream logfile;
	  logfile.open("receiver_log.txt");
	  logfile << " --- \n";

  const char* hname = "localhost";  

  //configure receiving port     
  Address * my_addr = new Address(hname, (short)(atoi(argv[1])));
  
  LossyReceivingPort *my_port = new LossyReceivingPort(0.2);
  my_port->setAddress(my_addr);
  my_port->init();

  //configure a sending port to send ACK
  Address * my_tx_addr = new Address(hname, 3005);
  Address * dst_addr =  new Address(argv[2], (short)(atoi(argv[3])));
  mySendingPort *my_tx_port = new mySendingPort();
  my_tx_port->setAddress(my_tx_addr);
  my_tx_port->setRemoteAddress(dst_addr);
  my_tx_port->init();
  
  Message *m = new Message();
  char *filename;
  char *filename_to_save = (char *) argv[4];
  
  cout << "begin receiving..." <<endl;
  Packet *p;
  int ackedSeqNum = 0;
  while (1)
  {
    p = my_port->receivePacket(); 
    if (p !=NULL)
    {  
    	switch(state){
    	case WAITING_STATE:{
    		int seqNum = p->accessHeader()->getIntegerInfo(m->SEQNUM_POS);
    		filename = p->getPayload();
    		Packet * ack_packet = m->make_ack_packet(seqNum);
    		cout << "receiving a packet of seq num " << seqNum << " and filename is " << filename << endl;
    		cout << "Beginning receiving file..." << endl;
    		my_tx_port->sendPacket(ack_packet);
    		remove("out.txt");
    		state = RECEIVING_STATE;
    		break;

    	}
    	case RECEIVING_STATE:{
    		// Stop-and-wait scheme
    		int seqNum = p->accessHeader()->getIntegerInfo(m->SEQNUM_POS);
    		cout << "receiving a packet of seq num " << seqNum << endl;
    		logfile << "Receive " << seqNum << "\n";
    		// special case, if being sent a seqnum = 0, which means the sender does not know
    		// receiver DID receive it, so we send ack again
    		if(seqNum != ackedSeqNum + 1){
    			Packet * ack_packet = m->make_ack_packet(seqNum);
    			cout << "The sender does not know we DID receive packet! Resend ACK for him... " << endl;
    			my_tx_port->sendPacket(ack_packet);
    			break;
    		}

    		char *payload = p->getPayload();
    		if(m->append_data_to_file(filename_to_save,payload,p->getPayloadSize())){//only when write to file success...
    			ackedSeqNum = seqNum;
    			Packet *ack_packet = m->make_ack_packet(seqNum);

        		my_tx_port->sendPacket(ack_packet); //... we send ACK
    		}

    		bool isEOF = p->accessHeader()->getShortIntegerInfo(m->EOF_POS) != 0 ? true : false;
    		cout << "isEOF? " << isEOF << endl;
    		if(isEOF){
    			cout << "Done receive file" <<endl;
    			logfile.close();
    		}
    		break;
    	}
    	default:
    		break;
    	}
    }
  } 
} catch (const char *reason ) {
    cerr << "Exception:" << reason << endl;
    exit(-1);
}  

return 0;
}
开发者ID:viethnguyen,项目名称:commnet2-project2,代码行数:100,代码来源:receiver.cpp

示例5: Sleep

HRESULT CVideoPin::FillBuffer(IMediaSample* pSample)
{
  try
  {
    Packet* buffer = NULL;

    do
    {
      if (m_pFilter->IsStopping() || m_demux.IsMediaChanging() || m_bFlushing || !m_bSeekDone || m_demux.m_bRebuildOngoing)
      {
        Sleep(1);
        return ERROR_NO_DATA;
      }

      if (m_demux.EndOfFile())
      {
        LogDebug("vid: set EOF");
        return S_FALSE;
      }

      if (m_demux.m_bVideoClipSeen || m_demux.m_bAudioRequiresRebuild && !m_demux.m_bVideoClipSeen && !m_demux.m_eAudioClipSeen->Check())
      {
        CheckPlaybackState();
        return ERROR_NO_DATA;
      }

      if (m_pCachedBuffer)
      {
        LogDebug("vid: cached fetch %6.3f clip: %d playlist: %d", m_pCachedBuffer->rtStart / 10000000.0, m_pCachedBuffer->nClipNumber, m_pCachedBuffer->nPlaylist);
        buffer = m_pCachedBuffer;
        m_pCachedBuffer = NULL;
        buffer->bDiscontinuity = true;
        
        if (m_bProvidePMT)
        {
          CMediaType mt(*buffer->pmt);
          SetMediaType(&mt);
          pSample->SetMediaType(&mt);
          m_bProvidePMT = false;
        }
      }
      else
        buffer = m_demux.GetVideo();

      if (!buffer)
      {
        if (m_bFirstSample)
          Sleep(10);
        else 
        {
          if (!m_bClipEndingNotified)
          {
            // Deliver end of stream notification to flush the video decoder.
            // This should only happen when the stream enters into paused state
            LogDebug("vid: FillBuffer - DeliverEndOfStream");
            DeliverEndOfStream();
            m_bClipEndingNotified = true;
          }
          else
            Sleep(10);
		  
          return ERROR_NO_DATA;
        }
      }
      else
      {
        bool checkPlaybackState = false;

        {
          CAutoLock lock(m_section);

          if (buffer->nNewSegment > 0)
          {
            if ((buffer->nNewSegment & NS_NEW_CLIP) == NS_NEW_CLIP)
            {
              LogDebug("vid: Playlist changed to %d - nNewSegment: %d offset: %6.3f rtStart: %6.3f rtPlaylistTime: %6.3f", 
                buffer->nPlaylist, buffer->nNewSegment, buffer->rtOffset / 10000000.0, buffer->rtStart / 10000000.0, buffer->rtPlaylistTime / 10000000.0);
            
              m_demux.m_bVideoClipSeen = true;
 
              m_bInitDuration = true;
              checkPlaybackState = true;
              m_bClipEndingNotified = false;

              if (buffer->bResuming || buffer->nNewSegment & NS_INTERRUPTED)
              {
                m_bDoFakeSeek = true;
                m_rtStreamOffset = buffer->rtPlaylistTime;
                m_bZeroTimeStream = true;
                m_demux.m_bAudioResetStreamPosition = true;
              }
              else
                m_rtStreamOffset = 0;

              // LAV video decoder requires an end of stream notification to be able to provide complete video frames
              // to downstream filters in a case where we are waiting for the audio pin to see the clip boundary as
              // we cannot provide yet the next clip's PMT downstream since audio stream could require a rebuild
              if (m_currentDecoder == CLSID_LAVVideo && (buffer->nNewSegment & NS_NEW_PLAYLIST))
              {
                LogDebug("DeliverEndOFStream LAV Only for audio pin wait (%d,%d)", buffer->nPlaylist, buffer->nClipNumber);
//.........这里部分代码省略.........
开发者ID:BMOTech,项目名称:MediaPortal-1,代码行数:101,代码来源:VideoPin.cpp

示例6: handle_uplink_udata

void Pgw::handle_uplink_udata(Packet pkt, UdpClient &sink_client) {
	pkt.truncate();
	sink_client.set_server(g_sink_ip_addr, g_sink_port);
	sink_client.snd(pkt);
	TRACE(cout << "pgw_handleuplinkudata:" << " uplink udata forwarded to sink: " << pkt.len << endl;)
}
开发者ID:networkedsystemsIITB,项目名称:NFV_LTE_EPC,代码行数:6,代码来源:pgw.cpp

示例7: Packet

Packet* CClip::GenerateSparseVideo(REFERENCE_TIME rtStart)
{
  Packet * ret = NULL;
  if (!SparseVideoAvailable() && m_vecClipVideoPackets.size()==0) return ret;
  if (m_pSparseVideoPacket != NULL)
  {
    if (m_vecClipVideoPackets.size()>0)
    {
      Packet * pBDPacket = m_vecClipVideoPackets[0];
      if (m_pSparseVideoPacket->rtStart + ONE_SECOND > pBDPacket->rtStart)
      {
        ivecVideoBuffers it = m_vecClipVideoPackets.begin();
        if ((*it)->rtStart !=Packet::INVALID_TIME)
        {
          delete m_pSparseVideoPacket;
          m_pSparseVideoPacket=*it;
          it=m_vecClipVideoPackets.erase(it);
        }
        else
        {
          it=m_vecClipVideoPackets.erase(it);
          if (!m_vecClipVideoPackets.size()) sparseVideo = false;
          return *it;
        }
      }
      else
      {
        m_pSparseVideoPacket->rtStart += HALF_SECOND/5;
        m_pSparseVideoPacket->rtStop += HALF_SECOND/5;
        m_pSparseVideoPacket->bFakeData = true;
      }
    }
    else
    {
      m_pSparseVideoPacket->rtStart += HALF_SECOND/5;
      m_pSparseVideoPacket->rtStop += HALF_SECOND/5;
      m_pSparseVideoPacket->bFakeData = true;
    }
    ret = new Packet();
    ret->SetData(m_pSparseVideoPacket->GetData(),m_pSparseVideoPacket->GetDataSize());
    ret->CopyProperties(*m_pSparseVideoPacket);
  }
  else
  {
    if (m_vecClipVideoPackets.size()>0)
    {
      ivecVideoBuffers it = m_vecClipVideoPackets.begin();
      if ((*it)->rtStart !=Packet::INVALID_TIME)
      {
        m_pSparseVideoPacket=*it;
        it=m_vecClipVideoPackets.erase(it);
        ret = new Packet();
        ret->SetData(m_pSparseVideoPacket->GetData(),m_pSparseVideoPacket->GetDataSize());
        ret->CopyProperties(*m_pSparseVideoPacket);
      }
      else
      {
        it=m_vecClipVideoPackets.erase(it);
        if (!m_vecClipVideoPackets.size()) sparseVideo = false;
        return *it;
      }
    }
  }
  return ret;
}
开发者ID:BMOTech,项目名称:MediaPortal-1,代码行数:65,代码来源:Clip.cpp

示例8: Packet

void CReadSendPacket::SendGameServerInfo (SOCKET Socket, SGameServer server)
{
	SPacket SPacket;

	//CryLog("[CryMasterServer] Send game server info...");

	Packet* p = new Packet();

	p->create();


	/****************************Обязательный блок************************************/

	p->writeInt(PACKET_GAME_SERVER);                     // Тип пакета
	p->writeString(gClientEnv->clientVersion);           // Версия пакета

	/*******************************Тело пакета****************************************/
                                    
	p->writeString(server.ip);                                
	p->writeInt(server.port);                               
	p->writeString(server.serverName);                       
	p->writeInt(server.currentPlayers);                   
	p->writeInt(server.maxPlayers);                     
	p->writeString(server.mapName);                          
	p->writeString(server.gameRules);                     

	p->writeString(EndBlock);                                    // Завершающий блок

	p->padPacketTo8ByteLen();
	p->encodeBlowfish(gClientEnv->bBlowFish);
	p->appendChecksum(false);
	p->appendMore8Bytes();


	int size = p->getPacketSize();
	char* packet = (char*)p->getBytesPtr();

	SPacket.addr = Socket;
	SPacket.data = packet;
	SPacket.size = size;

	gClientEnv->pPacketQueue->InsertPacket(SPacket);

	if(gClientEnv->bDebugMode)
	{
		CryLog("[CryMasterServer] Game Server info packet size = %d",size);
		CryLog("[CryMasterServer] Game Server ip = %s",server.ip);
		CryLog("[CryMasterServer] Game Server port = %d",server.port);
		CryLog("[CryMasterServer] Game Server name = %s",server.serverName);
		CryLog("[CryMasterServer] Game Server onlain = %d",server.currentPlayers);
		CryLog("[CryMasterServer] Game Server max players = %d",server.maxPlayers);
		CryLog("[CryMasterServer] Game Server map name = %s",server.mapName);
		CryLog("[CryMasterServer] Game Server gamerules = %s",server.gameRules);


		PacketDebugger::Debug(packet, size, "SendPacketsDebugg.txt");

	}
}
开发者ID:aronarts,项目名称:FireNET,代码行数:59,代码来源:SendPacket.cpp

示例9: Send

int
Send()
{
  int retVal = 1;

  if (gIpAddress == NULL)
  {
    cout << "Must specify at least a -d \"destination IP Address\"" << endl;
    cout << "e.g., trapgen -d 244.0.2.43" << endl;
    return 0;
  }
    
  if (gDump == ' ')
  {
    UdpClient udp(gPort, gIpAddress);
    if (gDoLogging)
      if (!udp.IsReady())
	gOfile << "udp failed to initialize with error " << udp.ErrorCode() << endl;
    udp.Send(&gPacket);
    if (gInform)
    {
      udp.Timeout(gTimeout);
      Packet* p = udp.Receive(0);

      if (p != NULL && 
	  (p->RequestId() == gRequestId) && 
	  (p->Type() == V1RESPONSE))
	retVal = 0;
      else
	if (gDoLogging)
	  gOfile << "Sent INFORM but response timed out (timeout = " << gTimeout << ')' << endl;
    }
    else
      retVal = 0;
  }
  else
  {
    if (gDump == 'a' || gDump == 'b')
    {
      cout << "Length: " << gPacket.TotalLength() << endl;
      int version = gPacket.Version();
      cout << "Version: ";
      if (version == 0)
	cout << "SNMPv1";
      else
	if (version == 1)
	  cout << "SNMPv2";
      cout << endl;

      cout << "Community: " << gPacket. Community() << endl;

      if (version == 0)
      {
	cout << "Generic: " << gPacket.GenericTrapType() << endl;
	cout << "Specific: " << gPacket.SpecificTrapType() << endl;
	////////////////////////////////////////////////////////
	int tTime = gPacket.TimeTicks();
	tTime /= 100;
	int days = tTime/(60*60*24);
	tTime -= days * (60*60*24);
	int hrs = tTime/(60*60);
	tTime -= hrs*(60*60);
	int mins = tTime/(60);
	tTime -= mins*(60);
	char newcTime[128];
#ifdef _WIN32
	sprintf_s(newcTime, 128, "%d days %02dh:%02dm:%02ds", days, hrs, mins, tTime);
#else
	sprintf(newcTime, "%d days %02dh:%02dm:%02ds", days, hrs, mins, tTime);
#endif
	cout << "TimeStamp: " << newcTime << " (" << gPacket.TimeTicks() << ")" << endl;
	// cout << "TimeStamp: " << gPacket.TimeTicks() << endl;
	////////////////////////////////////////////////////////
	cout << "SenderIP: " << gPacket.SenderIP() << endl;
      }

      if (version == 0)
	cout << "SenderOID: " << gPacket.SenderOID() << endl;

      int vblen = gPacket.VbListLength();
      for (int x = 1; x <= vblen; x++)
      {
	cout << "Varbind Number " << x << ' ' << endl;
	cout << '\t' << "Oid: " << gPacket.VbOID(x) << endl;
	cout << '\t' << "Type: " << gPacket.VbType(x) << endl;
	cout << '\t' << "Data: " << gPacket.VbData(x) << endl;
      }
      cout << endl;
    }

    if (gDump == 'h' || gDump == 'b')
    {
      unsigned int l = gPacket.TotalLength();
      unsigned char* pdu = new unsigned char[l];
      gPacket.Build(pdu);
      for (unsigned int asdf = 0; asdf < l; asdf++)
      {
	if (asdf && !(asdf % 10))
	  printf("\n");
	printf("%02x ", pdu[asdf]);
//.........这里部分代码省略.........
开发者ID:bigmacd,项目名称:trapgen,代码行数:101,代码来源:TrapGen.cpp

示例10: main


//.........这里部分代码省略.........
    ///////////////////////////////////////////////////
    // new to version 2.7
#ifdef _WIN32
    NtSysUpTime sysUpTime;
#endif
#ifdef _LINUX
    LinuxSysUpTime sysUpTime;
#endif
#ifdef _SOLARIS
    SolarisSysUpTime sysUpTime;
#endif
#ifdef _IRIX
    IrixSysUptime sysUpTime;
#endif
#ifdef _HPUX
    HpuxSysUpTime sysUpTime;
#endif
#ifdef _FREEBSD
    FreeBSDSysUptime sysUpTime;
#endif
    gTimeTicks = sysUpTime.SysUpTime();
    ///////////////////////////////////////////////////
    
    
    // figure out the ip address if not specified (V1 only)
    if (gSenderIP == NULL && gVersion == 0)
    {
      char buf[255];
      unsigned long len = 255;
      memset(buf, 0, len);
      if (gethostname(buf, len))
	if (gDoLogging)
	  gOfile << "gethostname failed with error " << WSAGetLastError() << endl;

      HOSTENT* h = gethostbyname(buf);
      if (h != NULL)
      {
	struct in_addr in;
	memcpy(&in.s_addr, *(h->h_addr_list), sizeof(in.s_addr));
	gSenderIP = inet_ntoa(in);
      }
      else
      {
	gSenderIP = "240.30.20.10";
	if (gDoLogging)
	  gOfile << "gethostbyname failed with error " << WSAGetLastError() << endl;
      }
    }

    // build the packet
    gPacket.Version(gVersion);
    gPacket.Community(gCommunity);
    if (gVersion == 0)
    {
      gPacket.Type(V1TRAP);
      gPacket.SenderOID(gSenderOID);
      gPacket.SenderIP(gSenderIP);
      gPacket.TimeTicks(gTimeTicks);
      gPacket.GenericTrapType(gGenericTrapType);
      gPacket.SpecificTrapType(gSpecificTrapType);
    }
    else
    {
      if (!gInform)
	gPacket.Type(V2TRAP);
      else
	gPacket.Type(INFORMPDU);

      gPacket.RequestId(gRequestId);
      gPacket.ErrorStatus(0);
      gPacket.ErrorIndex(0);
      gPacket.AddV2TrapVarbinds(gTimeTicks, 
				gSenderOID, 
				gGenericTrapType,
				gSpecificTrapType,
				gNoSubIds);
    }

    // send away
    retVal = Send();
    
  }
  catch (SnmpException* se)
  {
    retVal = -1;
  }
  catch (...)
  {
    retVal = -2;
  }

#ifdef _WIN32  
  WSACleanup();
#endif
  
  if (gDoLogging)
    gOfile.close();
  
  return retVal;
}
开发者ID:bigmacd,项目名称:trapgen,代码行数:101,代码来源:TrapGen.cpp

示例11: InitOption


//.........这里部分代码省略.........
      break;
    }

    case 'r':
    case 'R':
    {
      gRequestId = atoi(optionValue);
      break;
    }


    case 's':
    case 'S':
    {
      gSpecificTrapType = atoi(optionValue);
      break;
    }
    
    case 't':
    case 'T':
    {
      gTimeTicks = atoi(optionValue);
      break;
    }
    
    case 'v':
    case 'V':
    {
      OidVarbind* oid = new OidVarbind(optionValue);
      Varbind* vb;
      if (secondValue != NULL && thirdValue != NULL)
      {
	switch (secondValue[0])
	{
	  case 'S':
	  case 's':
	  {
	    vb = new StringVarbind(thirdValue);
	    break;
	  }
	  
	  case 'A':
	  case 'a':
	  {
	    vb = new IpAddrVarbind(thirdValue);
	    break;
	  }
  
  	  case 'O':
	  case 'o':
	  {
	    vb = new OidVarbind(thirdValue); 
	    break;
	  }
	  
	  case 'C':
	  case 'c':
	  {
	    vb = new CounterVarbind(atoi(thirdValue));
	    break;
	  }

	  case 'G':
	  case 'g':
	  {
	    vb = new GaugeVarbind(atoi(thirdValue));
	    break;
	  }

	  case 'H':
	  case 'h':
	  { 
	    vb = new StringVarbind(thirdValue, 0);
	    break;
	  }

	  case 'I':
	  case 'i':
	  {
	    vb = new IntVarbind(atoi(thirdValue));
	    break;
	  }

	  case 'T':
	  case 't':
	  { 
	    vb = new TimetickVarbind(atoi(thirdValue));
	    break;
	  }
	} // switch (argv[x+1])
	VbPair* vbp = new VbPair();                                 
	vbp->OIDVarbind(oid);
	vbp->VarBind(vb);
	//	gPacket->Add(vbp);
	gPacket.Add(vbp);
      } // if ((x + 1) < argc)
      break;
    }
  } // switch (opt)
}
开发者ID:bigmacd,项目名称:trapgen,代码行数:101,代码来源:TrapGen.cpp

示例12: WritePacketData

void Packet::WritePacketData(Packet &packet) {
	if (packet.Length() == 0) return;
	data.resize(data.size() + packet.Length());
	memcpy(&data[data.size() - packet.Length()], packet.Data(), packet.Length());
}
开发者ID:Leajian,项目名称:cspsp-nightly,代码行数:5,代码来源:Packet.cpp

示例13: resetPacketBuffer

/*! \sa PacketProcessor
 */
bool PacketProcessor::processFrame(Packet& p_Frame)
{
    //invalidate the packet by default
    m_Valid = false;    
    //invalidate the destination IP by default
    m_DestinationIP = ""; 
    //reset the processing buffer
    resetPacketBuffer();
    //get IP packet from the frame
    p_Frame.getPDU(m_PacketBuffer);

    //VALIDATE THE PACKET


    //check the link layer length 
    if((readShort(&m_PacketBuffer[3])) < MIN_LENGTH)
        {
            //Report and drop
            m_Converter.newReportString("Ilegal link layer length for packet: \n");
            m_Converter.appendReportString(readIPPacket());
            resetPacketBuffer();
            SC_REPORT_WARNING(g_ErrorID, m_Converter.getReportString());
            return false;
        }

    //verify checksum
    if(!(confirmCheckSum()))    
        {
            //Report and drop
            m_Converter.newReportString("Invalid CheckSum for packet: \n");
            m_Converter.appendReportString(readIPPacket());
            resetPacketBuffer();
            SC_REPORT_WARNING(g_ErrorID, m_Converter.getReportString());
            return false;
        }

    //verify the version
    if((readSubField(m_PacketBuffer[0], 7, 4) != VERSION))    
        {
            //Report and drop
            m_Converter.newReportString("Invalid protocol version for packet: \n");
            m_Converter.appendReportString(readIPPacket());
            resetPacketBuffer();
            SC_REPORT_WARNING(g_ErrorID, m_Converter.getReportString());
            return false;
        }

    //verify the IHL
    if((readSubField(m_PacketBuffer[0], 3, 0) < 5))
        {
            //Report and drop
            m_Converter.newReportString("Ilegal header length for packet: \n");
            m_Converter.appendReportString(readIPPacket());
            resetPacketBuffer();
            SC_REPORT_WARNING(g_ErrorID, m_Converter.getReportString());
            return false;
        }
        
    //verify the maximum length of the packet
    if((readShort(&m_PacketBuffer[3])) > MAX_LENGTH)    
        {
            //Report and drop
            m_Converter.newReportString("The packet length is too long: \n");
            m_Converter.appendReportString(readIPPacket());
            resetPacketBuffer();
            SC_REPORT_WARNING(g_ErrorID, m_Converter.getReportString());
            return false;
        }
    //store the destination address
    m_DestinationIP = m_Converter.ipToString(&m_PacketBuffer[16]);
    //validate the packet
    m_Valid = true;
    return true;
}
开发者ID:Keepalive-PP,项目名称:ProtocolProcessing_Group2,代码行数:76,代码来源:PacketProcessor.cpp

示例14: handle_create_session

void Pgw::handle_create_session(struct sockaddr_in src_sock_addr, Packet pkt) {
	uint64_t imsi;
	uint8_t eps_bearer_id;
	uint32_t s5_uteid_ul;
	uint32_t s5_uteid_dl;
	uint32_t s5_cteid_ul;
	uint32_t s5_cteid_dl;
	uint64_t apn_in_use;
	uint64_t tai;
	string ue_ip_addr;

	pkt.extract_item(s5_cteid_dl);
	pkt.extract_item(imsi);
	pkt.extract_item(eps_bearer_id);
	pkt.extract_item(s5_uteid_dl);
	pkt.extract_item(apn_in_use);
	pkt.extract_item(tai);
	s5_cteid_ul = s5_cteid_dl;
	s5_uteid_ul = s5_cteid_dl;
	ue_ip_addr = ip_addrs[imsi];
	update_itfid(5, s5_uteid_ul, "", imsi);
	update_itfid(0, 0, ue_ip_addr, imsi);

	g_sync.mlock(uectx_mux);
	ue_ctx[imsi].init(ue_ip_addr, tai, apn_in_use, eps_bearer_id, s5_uteid_ul, s5_uteid_dl, s5_cteid_ul, s5_cteid_dl);
	g_sync.munlock(uectx_mux);	

	pkt.clear_pkt();
	pkt.append_item(s5_cteid_ul);
	pkt.append_item(eps_bearer_id);
	pkt.append_item(s5_uteid_ul);
	pkt.append_item(ue_ip_addr);
	pkt.prepend_gtp_hdr(2, 1, pkt.len, s5_cteid_dl);
	s5_server.snd(src_sock_addr, pkt);
	TRACE(cout << "pgw_handlecreatesession:" << " create session response sent to mme: " << imsi << endl;)
}
开发者ID:networkedsystemsIITB,项目名称:NFV_LTE_EPC,代码行数:36,代码来源:pgw.cpp

示例15: main

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        cout << "Usage: " << argv[0] << " PORT-NUMBER FILE-NAME" << endl;
        exit(1);
    }

    ifstream file(argv[2]);
    int sockfd = set_up_socket(argv[1]);
    struct sockaddr_storage recv_addr;
    socklen_t addr_len = sizeof(recv_addr);
    int status, n_bytes;
    uint16_t ack_num, base_num;
    Packet p;

    unordered_map<uint16_t, Packet_info> window;
    Packet_info pkt_info;

    // select random seq_num
    srand(time(NULL));
    uint16_t seq_num = rand() % MSN;

    RTO rto;

    // recv SYN from client
    do
    {
        n_bytes = recvfrom(sockfd, (void *) &p, sizeof(p), 0, (struct sockaddr *) &recv_addr, &addr_len);
        process_error(n_bytes, "recv SYN");
    } while (!p.syn_set());
    cout << "Receiving packet " << p.ack_num() << endl;
    ack_num = (p.seq_num() + 1) % MSN;

    // sending SYN ACK
    p = Packet(1, 1, 0, seq_num, ack_num, 0, "", 0);
    pkt_info = Packet_info(p, n_bytes - HEADER_LEN, rto.get_timeout());
    status = sendto(sockfd, (void *) &p, HEADER_LEN, 0, (struct sockaddr *) &recv_addr, addr_len);
    process_error(status, "sending SYN ACK");
    cout << "Sending packet " << seq_num << " " << MSS << " " << INITIAL_SSTHRESH << " SYN" << endl;
    seq_num = (seq_num + 1) % MSN;
    base_num = seq_num;

    // recv ACK
    do
    {
        struct timeval max_time = pkt_info.get_max_time();
        struct timeval curr_time;
        gettimeofday(&curr_time, NULL);
        struct timeval time_left;
        timersub(&max_time, &curr_time, &time_left);
        status = setsockopt(sockfd, SOL_SOCKET,SO_RCVTIMEO, (char *)&time_left, sizeof(time_left));
        process_error(status, "setsockopt");
        n_bytes = recvfrom(sockfd, (void *) &p, sizeof(p), 0, (struct sockaddr *) &recv_addr, &addr_len);
        process_recv(n_bytes, "recv ACK after SYN ACK", sockfd, pkt_info, recv_addr, addr_len, rto);
    } while (p.seq_num() != ack_num); // discard invalid ack
    uint16_t prev_ack = p.ack_num();
    cout << "Receiving packet " << p.ack_num() << endl;
    ack_num = (p.seq_num() + 1) % MSN;

    double cwnd = min((double) MSS, MSN / 2.0);
    uint16_t cwnd_used = 0;
    uint16_t ssthresh = INITIAL_SSTHRESH;
    uint16_t cwd_pkts = 0;
    uint16_t pkts_sent = 0;
    uint16_t dup_ack = 0;
    uint16_t recv_window = UINT16_MAX;
    bool slow_start = true;
    bool congestion_avoidance = false;
    bool fast_recovery = false;
    bool retransmission = false;
    bool last_retransmit = false;
    // send file
    do
    {
        if (retransmission) // retransmit missing segment
        {
            auto found = window.find(base_num);
            p = found->second.pkt();
            status = sendto(sockfd, (void *) &p, found->second.data_len() + HEADER_LEN, 0, (struct sockaddr *) &recv_addr, addr_len);
            process_error(status, "sending retransmission");
            cout << "Sending packet " << p.seq_num() << " " << cwnd << " " << ssthresh << " Retransmission" << endl;
            retransmission = false;

            if (last_retransmit)
            {
                // double RTO if retransmission again
                rto.double_RTO();
            }
            found->second.update_time(rto.get_timeout());
            last_retransmit = true;
        }
        else // transmit new segment(s), as allowed
        {
            last_retransmit = false;
            while (floor(cwnd) - cwnd_used >= MSS && !file.eof())
            {
                string data;
                size_t buf_pos = 0;
                data.resize(MSS);
//.........这里部分代码省略.........
开发者ID:JasonYang96,项目名称:cs118-project2,代码行数:101,代码来源:server.cpp


注:本文中的Packet类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。