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


C++ recvfrom函数代码示例

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


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

示例1: output_sendto

static int output_sendto (int sock, const void *frame, int frame_size,
		struct sockaddr_in *addr)
{
	struct frame_info {
		int8_t 	mask[2];	// 'FM' const
		int32_t	len;	//
		int8_t	data[UDPDATA_MAX_SIZE];
	}__attribute__((__packed__));

	struct frame_info fm;
	fm.mask[0] = 'F';
	fm.mask[1] = 'M';
	fm.len = 0;

	unsigned char *p = NULL;
    p = (unsigned char *)frame;
    while(frame_size > 0) {
		static int cnt = 0;
    	if(frame_size < UDPDATA_MAX_SIZE)
    		fm.len = frame_size;
    	else
    		fm.len = UDPDATA_MAX_SIZE;

    	memcpy(fm.data, p, fm.len);
    	int i;
    	for(i = 0; i < 5; i++){
    		sendto(sock, &fm, sizeof(fm), 0, (struct sockaddr*)addr, sizeof(struct sockaddr_in));

    		char answer[128];
    		int len;
    		int ret;
    		fd_set input;
    		struct timeval timeout;
    		FD_ZERO(&input);
    		FD_SET(sock, &input);

    		timeout.tv_sec = 0;
    		timeout.tv_usec = 5000;
    		ret = select(sock + 1, &input, NULL, NULL, &timeout);
    		if (ret < 0) {
    			perror("select");
    			break;
    		} else if (ret == 0) {
				if(cnt == 0)
					printf("ERROR: no recv\n");
    			printf("%d\r", cnt++);
				fflush(stdout);
    		} else {
    			if (FD_ISSET(sock, &input)) {
					cnt = 0;
    	    		len = recvfrom(sock, answer, sizeof(answer), 0, NULL, 0);
    	    		if(len > 0)
    	    			if(strncmp(answer, "OK", 2) == 0)
    	    				break;
    			}
    		}

    	}
    	frame_size-=fm.len;
    	p += fm.len;
    }
    p = NULL;

    return 0;
}
开发者ID:crazyleen,项目名称:mjpeg-streamer,代码行数:65,代码来源:output_udp.c

示例2: getReplyPackets

int getReplyPackets(int method,int peer,int batchP,
		    struct response_set *responses,
		    unsigned char *transaction_id,int timeout)
{
  /* set timeout alarm */
  
  /* get packets until timeout, or until we get a packet from the specified peer
     if method==REQ_SERIAL.  If REQ_SERIAL we also reject packets from other 
     senders as they must be spoofs.
  */
  struct timeval t;
  int timeout_secs;
  int timeout_usecs;
  int to=timeout;

  if (debug>1) printf("getReplyPackets(policy=%d)\n",method);

  /* Work out when the timeout will expire */
  gettimeofday(&t,NULL); 
  timeout_secs=t.tv_sec; timeout_usecs=t.tv_usec;
  if (to>1000) { timeout_secs+=(to/1000); to=to%1000; }
  timeout_usecs+=to*1000; if (timeout_usecs>1000000) { timeout_secs++; timeout_usecs-=1000000; }
  
  while(1) {
    unsigned char buffer[16384];
    socklen_t recvaddrlen=sizeof(recvaddr);
    struct pollfd fds;
    client_port=((struct sockaddr_in*)&recvaddr)->sin_port;
    bzero((void *)&recvaddr,sizeof(recvaddr));
    fds.fd=sock; fds.events=POLLIN;
    while (poll(&fds,1,10 /* wait for 10ms at a time */)<1)
      {
	gettimeofday(&t,NULL);
	if (t.tv_sec>timeout_secs) return 1;
	if (t.tv_sec==timeout_secs&&t.tv_usec>=timeout_usecs) return 1;
      }
    client_port=((struct sockaddr_in*)&recvaddr)->sin_port;
    int len=recvfrom(sock,buffer,sizeof(buffer),0,&recvaddr,&recvaddrlen);
    client_addr=((struct sockaddr_in*)&recvaddr)->sin_addr;
    if (debug) fprintf(stderr,"Received reply from %s (len=%d).\n",inet_ntoa(client_addr),len);
    if (debug>1) dump("recvaddr",(unsigned char *)&recvaddr,recvaddrlen);
    if (debug>2) dump("packet",(unsigned char *)buffer,len);
    if (dropPacketP(len)) {
      if (debug) fprintf(stderr,"Simulation mode: Dropped packet due to simulated link parameters.\n");
      continue;
    }
    if (!packetOk(buffer,len,transaction_id)) {
      /* Packet passes tests - extract responses and append them to the end of the response list */
      if (extractResponses(client_addr,buffer,len,responses)) 
	return setReason("Problem extracting response fields from reply packets");
      if (method==REQ_SERIAL||method==REQ_FIRSTREPLY) {
	if (!batchP) return 0;
	/* In batch mode we need ACTION_DONE to mark end of transmission. 
	   While it gets sent last, out-of-order delivery means we can't rely on
	   such a nice arrangement. */
	{
	  /* XXX inefficient for long lists.
	     XXX can be made better by working backwards from end using double-linked list and 
	     remembering the previous length of the list */
	  struct response *r=responses->responses;
	  while(r)
	    {
	      if (r->code==ACTION_DONE) return 0;
	      r=r->next;
	    }
	}
      }
      else {
	if (debug>1) printf("Waiting for more packets, since called with policy %d\n",method);
      }
    } else {
      if (debug) setReason("Ignoring invalid packet");
    }      
  }
}
开发者ID:tseeley,项目名称:serval-dna,代码行数:75,代码来源:client.c

示例3: helper_child

/* helper processes start here via fork()/exec() in the parent  */
void DCC_NORET
helper_child(DCC_SOCKET s, int fd, int total_helpers)
{
	sigset_t sigs;
	socklen_t soc_len;
	DNSBL_REQ req;
	int req_len;
	DNSBL_RESP resp;
	DCC_SOCKU req_su;
	socklen_t su_len;
	struct timeval now;
	u_char wake_buf;
	int secs, i;

	/* this process inherits via exec() by dccm or dccifd odd signal
	 * blocking from some pthreads implementations including FreeBSD 5.* */
	signal(SIGHUP, SIG_IGN);
	signal(SIGINT, SIG_IGN);
	signal(SIGTERM, SIG_IGN);
	sigemptyset(&sigs);
	sigaddset(&sigs, SIGALRM);
	sigprocmask(SIG_UNBLOCK, &sigs, 0);

	helper_init(0);
	if (have_helpers)
		dcc_logbad(EX_SOFTWARE, "no threads for DNSBL helpers");

	helper.total_helpers = total_helpers;

	helper.pipe_read = fd;
	helper.soc = s;
	soc_len = sizeof(helper.su);
	if (0 > getsockname(helper.soc, &helper.su.sa, &soc_len))
		dcc_logbad(EX_IOERR, "DNSBL helper getsockname(%d): %s",
			   helper.soc, ERROR_STR());

	if (helper.debug > 1)
		dcc_trace_msg("DNSBL helper process starting on %s",
			      dcc_su2str_err(&helper.su));

	for (;;) {
		/* Use read() and SIGALRM to watch for a wake-up byte
		 * from the parent, the parent ending and closing the pipe,
		 * or enough idle time to require our retirement.  This
		 * tactic awakens a single child for each wake-up call
		 * from the parent.  Using select() or poll() on the main
		 * socket awakens a thundering herd of children */
		secs = HELPER_IDLE_STOP_SECS+1;
		if (helper.total_helpers > 0)
			secs /= helper.total_helpers+1;
		if (secs < 5)
			secs = 5;
		signal(SIGALRM, helper_alarm);
#ifdef HAVE_SIGINTERRUPT
		siginterrupt(SIGALRM, 1);
#endif
		helper_alarm_hit = 0;
		alarm(secs);
		for (;;) {
			su_len = sizeof(req_su);
			req_len = recvfrom(helper.soc, &req, ISZ(req), 0,
					   &req_su.sa, &su_len);

			/* sleep until awakened if no work is ready */
			if (req_len <= 0) {
				if (req_len == 0)
					dcc_logbad(EX_IOERR,
						   "DNSBL helper recvfrom()=0");
				if (!DCC_BLOCK_ERROR())
					dcc_logbad(EX_IOERR,
						   "DNSBL helper recvfrom():"
						   " %s",
						   ERROR_STR());
				if (helper_alarm_hit)
					helper_exit("idle helper exit");

				i = read(helper.pipe_read, &wake_buf, 1);

				/* The other end of the pipe can be marked
				 * non-blocking by some pthreads
				 * implementations.  That makes read() on this
				 * end fail with EAGAIN.  When that happens,
				 * fall back on select() or poll().
				 * Even on such pthread implementations,
				 * it rarely happens. */
				if (i < 0 && DCC_BLOCK_ERROR()) {
					DCC_POLLFD pollfd;
					DCC_EMSG emsg;

					pollfd.fd = helper.pipe_read;
					i = select_poll(emsg, &pollfd, 1,
							0, -1);
					if (i < 0)
					    dcc_logbad(EX_IOERR,
						       "dnsbl HELPER %s", emsg);
				}

				/* loof for work after a wake-up call */
				if (i > 0)
//.........这里部分代码省略.........
开发者ID:Gelma,项目名称:DCC_for_Jonas,代码行数:101,代码来源:helper.c

示例4: dtls_server

void dtls_server (int port)
{
    int listen_sd;
    int sock, ret;
    struct sockaddr_in sa_serv;
    char buffer[MAX_MESSAGE_SIZE];
    int mtu = 1400;
    unsigned char sequence[8];
    gnutls_datum_t cookie_key; // Should this be regenerated for each incoming conn?
    
    // Certs
    char *cafile = "./certs/cert.pem";
    char *crlfile = "./certs/crl.pem";
    char *certfile = "./certs/cert.pem";
    char *keyfile = "./certs/key.pem";
    
    // Configure credentials and session
    gnutls_certificate_allocate_credentials (&x509_cred);
    gnutls_certificate_set_x509_trust_file (x509_cred, cafile, GNUTLS_X509_FMT_PEM);
    gnutls_certificate_set_x509_crl_file (x509_cred, crlfile, GNUTLS_X509_FMT_PEM);
    ret = gnutls_certificate_set_x509_key_file (x509_cred, certfile, keyfile,
                                          GNUTLS_X509_FMT_PEM);
    if (ret < 0) Die("No keys or certs were found");
    
    // Set some crypto params and other stuff
    generate_dh_params (); // Diffie-Hellman
    gnutls_priority_init (&priority_cache,
            "PERFORMANCE:-VERS-TLS-ALL:+VERS-DTLS1.0:%SERVER_PRECEDENCE", 
            NULL);
    gnutls_key_generate (&cookie_key, GNUTLS_COOKIE_KEY_SIZE);
    
    /* Socket operations
     */
    listen_sd = socket (AF_INET, SOCK_DGRAM, 0);

    memset (&sa_serv, '\0', sizeof (sa_serv));
    sa_serv.sin_family = AF_INET;
    sa_serv.sin_addr.s_addr = INADDR_ANY;
    sa_serv.sin_port = htons (port);

/* DTLS requires the IP don't fragment (DF) bit to be set */
#if defined(IP_DONTFRAG)
      int optval = 1;
      setsockopt (listen_sd, IPPROTO_IP, IP_DONTFRAG,
                  (const void *) &optval, sizeof (optval));
#elif defined(IP_MTU_DISCOVER)
      int optval = IP_PMTUDISC_DO;
      setsockopt(listen_sd, IPPROTO_IP, IP_MTU_DISCOVER, 
                 (const void*) &optval, sizeof (optval));
#endif

    bind (listen_sd, (struct sockaddr *) &sa_serv, sizeof (sa_serv));

    printf ("UDP server ready. Listening to port '%d'.\n\n", port);
    
    for (;;)
    {
        printf ("Waiting for connection...\n");

        sock = wait_for_connection (listen_sd);
        if (sock < 0) continue;

        // Someone is accepting a connection, get data structures ready
        priv_data_st priv;
        gnutls_dtls_prestate_st prestate;
        gnutls_session_t session;
        struct sockaddr_in cli_addr;
        socklen_t cli_addr_size;

        cli_addr_size = sizeof (cli_addr);
        ret = recvfrom (sock, buffer, sizeof (buffer), MSG_PEEK,
                        (struct sockaddr *) &cli_addr, &cli_addr_size);
        if (ret > 0)
        {
            memset (&prestate, 0, sizeof (prestate));
            ret = gnutls_dtls_cookie_verify (&cookie_key, &cli_addr,
                                             sizeof (cli_addr), buffer, ret,
                                             &prestate);
            if (ret < 0) /* cookie not valid */
            {
                priv_data_st s;

                memset (&s, 0, sizeof (s));
                s.fd = sock;
                s.cli_addr = (void *) &cli_addr;
                s.cli_addr_size = sizeof (cli_addr);

                printf ("Sending hello verify request to %s\n",
                        human_addr ((struct sockaddr *) &cli_addr,
                                    sizeof (cli_addr), buffer,
                                    sizeof (buffer)));

                gnutls_dtls_cookie_send (&cookie_key, &cli_addr,
                                         sizeof (cli_addr), &prestate,
                                         (gnutls_transport_ptr_t) & s,
                                         push_func);

                /* discard peeked data */
                recvfrom (sock, buffer, sizeof (buffer), 0,
                          (struct sockaddr *) &cli_addr, &cli_addr_size);
//.........这里部分代码省略.........
开发者ID:a34729t,项目名称:exp,代码行数:101,代码来源:dtls_echo.c

示例5: HandleSecure

/** void HandleSecure() v0.3
 * Handle the secure connections
 */
void HandleSecure()
{
    int agentid;

    char buffer[OS_MAXSTR +1];
    char cleartext_msg[OS_MAXSTR +1];
    char srcip[IPSIZE +1];
    char *tmp_msg;
    char srcmsg[OS_FLSIZE +1];


    int recv_b;

    struct sockaddr_in peer_info;
    socklen_t peer_size;


    /* Send msg init */
    send_msg_init();


    /* Initializing key mutex. */
    keyupdate_init();


    /* Initializing manager */
    manager_init(0);


    /* Creating Ar forwarder thread */
    if(CreateThread(AR_Forward, (void *)NULL) != 0)
    {
        ErrorExit(THREAD_ERROR, ARGV0);
    }

    /* Creating wait_for_msgs thread */
    if(CreateThread(wait_for_msgs, (void *)NULL) != 0)
    {
        ErrorExit(THREAD_ERROR, ARGV0);
    }


    /* Connecting to the message queue
     * Exit if it fails.
     */
    if((logr.m_queue = StartMQ(DEFAULTQUEUE,WRITE)) < 0)
    {
        ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQUEUE);
    }


    verbose(AG_AX_AGENTS, ARGV0, MAX_AGENTS);


    /* Reading authentication keys */
    verbose(ENC_READ, ARGV0);

    OS_ReadKeys(&keys);

    debug1("%s: DEBUG: OS_StartCounter.", ARGV0);
    OS_StartCounter(&keys);
    debug1("%s: DEBUG: OS_StartCounter completed.", ARGV0);


    /* setting up peer size */
    peer_size = sizeof(peer_info);
    logr.peer_size = sizeof(peer_info);


    /* Initializing some variables */
    memset(buffer, '\0', OS_MAXSTR +1);
    memset(cleartext_msg, '\0', OS_MAXSTR +1);
    memset(srcmsg, '\0', OS_FLSIZE +1);
    tmp_msg = NULL;



    /* loop in here */
    while(1)
    {
        /* Receiving message  */
        recv_b = recvfrom(logr.sock, buffer, OS_MAXSTR, 0,
                (struct sockaddr *)&peer_info, &peer_size);


        /* Nothing received */
        if(recv_b <= 0)
        {
            continue;
        }


        /* Setting the source ip */
        strncpy(srcip, inet_ntoa(peer_info.sin_addr), IPSIZE);
        srcip[IPSIZE] = '\0';


//.........这里部分代码省略.........
开发者ID:Ar0xA,项目名称:ossec-hids,代码行数:101,代码来源:secure.c

示例6: rtp_read

static int rtp_read(URLContext *h, uint8_t *buf, int size)
{
	RTPContext *s = h->priv_data;
	struct sockaddr_storage from;
	socklen_t from_len;
	int len, n;
	struct pollfd p[2] = {{s->rtp_fd, POLLIN, 0}, {s->rtcp_fd, POLLIN, 0}};

#if 0
	for(;;)
	{
		from_len = sizeof(from);
		len = recvfrom (s->rtp_fd, buf, size, 0,
		(struct sockaddr *)&from, &from_len);
		if (len < 0)
		{
			if (ff_neterrno() == AVERROR(EAGAIN) ||
			ff_neterrno() == AVERROR(EINTR))
				continue;
			return AVERROR(EIO);
		}
		break;
	}
#else
	for(;;)
	{
		if (url_interrupt_cb())
			return AVERROR_EXIT;
		/* build fdset to listen to RTP and RTCP packets */
		n = poll(p, 2, 100);
		if (n > 0)
		{
			/* first try RTCP */
			if (p[1].revents & POLLIN)
			{
				from_len = sizeof(from);
				len = recvfrom (s->rtcp_fd, buf, size, 0,
				(struct sockaddr *)&from, &from_len);
				if (len < 0)
				{
					if (ff_neterrno() == AVERROR(EAGAIN) ||
					ff_neterrno() == AVERROR(EINTR))
						continue;
					return AVERROR(EIO);
				}
				break;
			}
			/* then RTP */
			if (p[0].revents & POLLIN)
			{
				from_len = sizeof(from);
				len = recvfrom (s->rtp_fd, buf, size, 0,
				(struct sockaddr *)&from, &from_len);
				if (len < 0)
				{
					if (ff_neterrno() == AVERROR(EAGAIN) ||
					ff_neterrno() == AVERROR(EINTR))
						continue;
					return AVERROR(EIO);
				}
				break;
			}
		}
		else if (n < 0)
		{
			if (ff_neterrno() == AVERROR(EINTR))
				continue;
			return AVERROR(EIO);
		}
	}
#endif
	return len;
}
开发者ID:hicks0074,项目名称:freescale_omx_framework,代码行数:73,代码来源:rtpproto.c

示例7: receive_callback

/* Callback function executed when something is received on fd */
int receive_callback(int file, void *arg) {
  char buf[sizeof(struct rudp_packet)];
  struct sockaddr_in sender;
  size_t sender_length = sizeof(struct sockaddr_in);
  recvfrom(file, &buf, sizeof(struct rudp_packet), 0, (struct sockaddr *)&sender, &sender_length);

  struct rudp_packet *received_packet = malloc(sizeof(struct rudp_packet));
  if(received_packet == NULL) {
    fprintf(stderr, "receive_callback: Error allocating packet\n");
    return -1;
  }
  memcpy(received_packet, &buf, sizeof(struct rudp_packet));
  
  struct rudp_hdr rudpheader = received_packet->header;
  char type[5];
  short t = rudpheader.type;
  if(t == 1)
    strcpy(type, "DATA");
  else if(t == 2)
    strcpy(type, "ACK");
  else if(t == 4)
    strcpy(type, "SYN");
  else if(t==5)
    strcpy(type, "FIN");
  else
    strcpy(type, "BAD");

  printf("Received %s packet from %s:%d seq number=%u on socket=%d\n",type, 
       inet_ntoa(sender.sin_addr), ntohs(sender.sin_port),rudpheader.seqno,file);

  /* Locate the correct socket in the socket list */
  if(socket_list_head == NULL) {
    fprintf(stderr, "Error: attempt to receive on invalid socket. No sockets in the list\n");
    return -1;
  }
  else {
    /* We have sockets to check */
    struct rudp_socket_list *curr_socket = socket_list_head;
    while(curr_socket != NULL) {
      if((int)curr_socket->rsock == file) {
        break;
      }
      curr_socket = curr_socket->next;
    }
    if((int)curr_socket->rsock == file) {
      /* We found the correct socket, now see if a session already exists for this peer */
      if(curr_socket->sessions_list_head == NULL) {
        /* The list is empty, so we check if the sender has initiated the protocol properly (by sending a SYN) */
        if(rudpheader.type == RUDP_SYN) {
          /* SYN Received. Create a new session at the head of the list */
          u_int32_t seqno = rudpheader.seqno + 1;
          create_receiver_session(curr_socket, seqno, &sender);
          /* Respond with an ACK */
          struct rudp_packet *p = create_rudp_packet(RUDP_ACK, seqno, 0, NULL);
          send_packet(true, (rudp_socket_t)file, p, &sender);
          free(p);
        }
        else {
          /* No sessions exist and we got a non-SYN, so ignore it */
        }
      }
      else {
        /* Some sessions exist to be checked */
        bool_t session_found = false;
        struct session *curr_session = curr_socket->sessions_list_head;
        struct session *last_session;
        while(curr_session != NULL) {
          if(curr_session->next == NULL) {
            last_session = curr_session;
          }
          if(compare_sockaddr(&curr_session->address, &sender) == 1) {
            /* Found an existing session */
            session_found = true;
            break;
          }

          curr_session = curr_session->next;
        }
        if(session_found == false) {
          /* No session was found for this peer */
          if(rudpheader.type == RUDP_SYN) {
            /* SYN Received. Send an ACK and create a new session */
            u_int32_t seqno = rudpheader.seqno + 1;
            create_receiver_session(curr_socket, seqno, &sender);          
            struct rudp_packet *p = create_rudp_packet(RUDP_ACK, seqno, 0, NULL);
            send_packet(true, (rudp_socket_t)file, p, &sender);
            free(p);
          }
          else {
            /* Session does not exist and non-SYN received - ignore it */
          }
        }
        else {
          /* We found a matching session */ 
          if(rudpheader.type == RUDP_SYN) {
            if(curr_session->receiver == NULL || curr_session->receiver->status == OPENING) {
              /* Create a new receiver session and ACK the SYN*/
              struct receiver_session *new_receiver_session = malloc(sizeof(struct receiver_session));
              if(new_receiver_session == NULL) {
//.........这里部分代码省略.........
开发者ID:AfifFaris,项目名称:Reliable-UDP,代码行数:101,代码来源:rudp.c

示例8: handshake

/*  The server waits for client to send its initial sequence number,
 send its own initial sequence number,
 and returns the client's initial sequence number. */
uint16_t handshake(int sockfd, struct sockaddr_in &clientaddr, socklen_t clientlen)
{
    unsigned char handshake_buf[HEADERSIZE];
    segment syn, ack;
    
    // receive syn
    long recv_len;
    if ((recv_len = recvfrom(sockfd, handshake_buf, HEADERSIZE, 0,
                             (struct sockaddr *) &clientaddr, &clientlen)) < 8)
    {
        cerr << "syn error" << endl;
        return USHRT_MAX;
    }

    syn.decode(handshake_buf, HEADERSIZE);
    if (syn.getFlagsyn())
    {
        server_seq = server_ack = seq_rand(MAX_SEQ_NUM);

        bool firstSyn = true;
        do {// send syn-ack
            segment synack;
            synack.setSeqnum(server_seq);
            setReplyAck(syn, synack, 1);
            client_ack = synack.getAcknum();
            synack.setFlagsyn();
            synack.setFlagack();
            
            unsigned char *handshake_buf2 = synack.encode(NULL, 0);
            sendto(sockfd, handshake_buf2, HEADERSIZE, 0,
                   (struct sockaddr *) &clientaddr, clientlen);
            
            if (firstSyn)
            {
                cout << "Sending packet " << server_seq << " " << cwnd << " " << ssthresh
                << " SYN" << endl;
                firstSyn = false;
            }
            else
            {
                cout << "Sending packet " << server_seq << " " << cwnd << " " << ssthresh
                << " Retransmission SYN" << endl;
            }
            
            clock_t clock_begin, clock_end;
            clock_begin = clock_end = clock();
            double elapsed_secs = 0.0;
            
            // receive ack
            while ((recv_len = recvfrom(sockfd, handshake_buf, HEADERSIZE, MSG_DONTWAIT,
                                        (struct sockaddr *) &clientaddr, &clientlen)) == -1)
            {
                if (errno != EWOULDBLOCK && errno != EAGAIN)
                    perror("recvfrom");
                clock_end = clock();
                elapsed_secs = double(clock_end - clock_begin) / CLOCKS_PER_SEC;
                if (elapsed_secs >= timeout)
                    break;
            }
            if (elapsed_secs < timeout)
            {
                ack.decode(handshake_buf, HEADERSIZE);
                if (ack.getFlagsyn())
                    continue;
                else
                    break;
            }
            
        } while (true);
        
        server_seq = (server_seq + 1) % MAX_SEQ_NUM;
        
        if (ack.getFlagack() && ack.getAcknum() == server_seq)
        {
            cout << "Receiving packet " << ack.getAcknum() << endl;
            
            server_ack = ack.getAcknum();
            return client_ack;
        }
        else
        {
            cout << "ACK flag: " << ack.getFlagack() << endl;
            cout << "SYN flag: " << ack.getFlagsyn() << endl;
            cout << "ack num received: " << ack.getAcknum() << endl;
            cout << "global_seq: " << server_seq << endl;
            cerr << "ack flag error or acknum error" << endl;
            return USHRT_MAX;
        }
    }
    else
    {
        cerr << "syn flag error" << endl;
        return USHRT_MAX;
    }
}
开发者ID:Brick-Mover,项目名称:S16_CS118_project2_TcpOverUdp,代码行数:98,代码来源:server.cpp

示例9: get_myip

/* return -1 and set myip to empty string if failed to get it */
int get_myip(char *myip) {

	/* define local static variables */
	static unsigned char tries = 0;
	//static unsigned char timeout = 1;
	static int myip_sockfd;
	static struct hostent *myip_server_ent;
	static struct sockaddr_in myip_servaddr;
	static char data[] = "\n";
	static char tmpip[IPADDR_LEN];
	static ssize_t n;	/* TODO: may use a global var */
	//static struct sigaction action;
	static struct timeval tv;  /* TODO: may use a global var */

	/* init vars */
	tries = 0;
	tv.tv_sec = MYIP_TIMEOUT;
	tv.tv_usec = 0;
	bzero(tmpip, IPADDR_LEN);
	// bzero(myip, IPADDR_LEN);
	*myip = '\0';
	bzero(&myip_servaddr, sizeof(myip_servaddr));
	myip_servaddr.sin_family = AF_INET;
	myip_servaddr.sin_port = htons(myip_server_port);


	/* initialise signal handler
	bzero(&action, sizeof(action));
	action.sa_handler = timed_out;
	action.sa_flags = 0;
	sigaction(SIGALRM, &action, 0); */

	/* get IP of myip_server, and setup myip_servaddr */
	myip_server_ent = gethostbyname(myip_server);
	if (myip_server_ent == NULL) {
		logwrite("get_myip: Error resolving myip_server!");
		return(-1);
	}
	memcpy(&myip_servaddr.sin_addr.s_addr, myip_server_ent->h_addr_list[0], myip_server_ent->h_length);

	myip_sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	setsockopt(myip_sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));

	/* try a few times to read myip */
	while (tries < MAX_MYIP_TRIES) {
		sendto(myip_sockfd, data, 1, 0, (SA *)&myip_servaddr, sizeof(myip_servaddr));
		//alarm(MYIP_TIMEOUT);
		if((n = recvfrom(myip_sockfd, tmpip, IPADDR_LEN, 0, NULL, NULL)) <= 0) {
			if (log_verbose) logwrite("get_myip: Timeout reading myip_server");
			++tries;
		} else {
			chomp(tmpip);
			if (log_verbose) {
				sprintf(msg, "get_myip: %s", tmpip);
				logwrite(msg);
			}
			break;  /* got answer packet */
		}
	}

	//alarm(0);
	close(myip_sockfd);

	/* make sure tmpip is in correct format */
	if (sscanf(tmpip, "%u.%u.%u.%u", &int_tmp,&int_tmp,&int_tmp,&int_tmp) != 4) {
		return(-1);
	} else {
		strncpy(myip, tmpip, IPADDR_LEN);
		return(0);
	}
}
开发者ID:michaelfung,项目名称:miniupdate,代码行数:72,代码来源:misc.c

示例10: main


//.........这里部分代码省略.........
	exit(1);
}; // end if


// init outbuffer
// set pointer dstkheader to beginning of buffer
dstkhead_out = (dstkheader_str *) sendbuffer;
dstkdata = (void *) sendbuffer + sizeof(dstkheader_str);

// fill in fixed parts 
dstkhead_out->version=1;

// this version of this application only contains one single DSTK-subframe
// inside one superframe. So, "last" is set to 1
dstkhead_out->flags = DSTK_FLG_LAST;


streamid=0;
packetsequence=0;

while (forever) {
	// some local vars
	int foundit;
	int giveup;
	int dstkheaderoffset;
	int thisorigin;
 	int otherfound;


	// Start receiving data from multicast stream
	// The payload of the ipv6 multicast-stream are the ipv4
	// UDP packets exchanged by the gateway-server and the
	// repeater controller	
	packetsize=recvfrom(sock_in,receivebuffer,ETHERNETMTU,0,NULL,0);

	if (packetsize == -1) {
		// no data received. Wait 2 ms and try again
		usleep(2000);
		continue;
	}; // end if

	// We should have received at least 20 octets (the size of the DSTK-header)
	if (packetsize < 20) {
		fprintf(stderr,"Packetsize to small! \n");
		continue;
	}; // end if


	// check packet: We should find a DSTK frame:
	foundit=0; giveup=0; dstkheaderoffset=0; otherfound=0;

	while ((! foundit) && (! giveup)) {
		// check DSTK packet header
		dstkhead_in = (dstkheader_str *) (receivebuffer + dstkheaderoffset);

		if (dstkhead_in->version != 1) {
			fprintf(stderr,"DSTK header version 1 expected. Got %d\n",dstkhead_in->version);
			giveup=1;
			break;
		} else if ((ntohl(dstkhead_in->type) & TYPEMASK_FILT_NOFLAGS) == TYPE_RPC_IP) {
			// OK, found Ethernet frames of RPC-stream
			foundit=1;
			break;
		};

		// OK, we found something, but it's not what we are looking for
开发者ID:EQ4,项目名称:DSTK,代码行数:67,代码来源:rpc2amb.c

示例11: main


//.........这里部分代码省略.........
                send_size = BUFSIZE;
            else
                send_size = (int)(maxbyte - lastbyteSent);
            
            if (lastbyteSentPtr + send_size > file_buf + MAX_SEQ_NUM_HALF)
            {
                unsigned char temp[BUFSIZE];
                long send_part2 = (lastbyteSentPtr + send_size) - (file_buf + MAX_SEQ_NUM_HALF);
                long send_part1 = send_size - send_part2;
                memcpy((char*)temp, (char*)lastbyteSentPtr, send_part1);
                memcpy((char*)(temp+send_part1), (char*)file_buf, send_part2);
                unsigned char *send_buf = seg.encode(temp, send_size);
                sendto(sockfd, send_buf, send_size+HEADERSIZE, 0, (struct sockaddr *)&clientaddr, clientlen);
                lastbyteSentPtr = lastbyteSentPtr + send_size - MAX_SEQ_NUM_HALF;
            }
            else
            {
                unsigned char *send_buf = seg.encode(lastbyteSentPtr, send_size);
                sendto(sockfd, send_buf, send_size+HEADERSIZE, 0, (struct sockaddr *)&clientaddr, clientlen);
                lastbyteSentPtr = lastbyteSentPtr + send_size;
            }
            
            clock_t now = clock();
            time_map[server_seq] = now;
            
            cout << "Sending packet " << server_seq << " " << cwnd << " " << ssthresh << endl;
            server_seq = (server_seq + send_size) % MAX_SEQ_NUM;
        }
        
        while (true)
        {
            unsigned char recv_buf[HEADERSIZE];
            long recv_len;
            if ((recv_len = recvfrom(sockfd, recv_buf, HEADERSIZE, MSG_DONTWAIT,
                                     (struct sockaddr *) &clientaddr, &clientlen)) == -1)
            {
                if (errno != EWOULDBLOCK && errno != EAGAIN)
                    perror("recvfrom");
                break;
            }
            
            segment ack;
            ack.decode(recv_buf, HEADERSIZE);
            if (ack.getFlagack())
            {
                cout << "Receiving packet " << ack.getAcknum() << endl;
                
                if (ack.getAcknum() != server_ack)
                {
                    map<uint16_t, clock_t>::iterator it = time_map.find(server_ack);
                    if (it != time_map.end())
                    {
                        clock_t now, then;
                        now = clock();
                        then = it->second;
                        time_map.erase(server_ack);
                        
                        double sampleRTT = double(now - then) / CLOCKS_PER_SEC;
                        
                        if (firstRTT)
                        {
                            estimatedRTT = sampleRTT;
                            devRTT = sampleRTT / 2;
                            adaptiveRTO = estimatedRTT + 4 * devRTT;
                            timeout = adaptiveRTO;
                            firstRTT = false;
开发者ID:Brick-Mover,项目名称:S16_CS118_project2_TcpOverUdp,代码行数:67,代码来源:server.cpp

示例12: slave_update

slave_event_t slave_update(data_t *command, data_t *answer)
{
    struct timeval timeout = {
        .tv_sec = 0,
        .tv_usec = 10000
    };
    struct sockaddr_in dev_addr = {
        .sin_family = AF_INET,
        .sin_port = htons(PORT_SLAVE),
    };
    int8_t pkg[OPTIONS_NUM * sizeof(int32_t)] = {};
    int len = sizeof(pkg), addr_len = sizeof(struct sockaddr_in);
    int sockfd;
    
    if (!serialize_cb || !deserialize_cb)
        return SLAVE_INIT_ERROR;

    if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
    {
        perror("\n Error : Could not create socket \n");
        return SLAVE_NETWORK_ERROR;
    }

    if (serialize_cb(command, pkg, &dev_addr) != SLAVE_DATA)
        return SLAVE_DATA_ERROR;

#ifdef SLAVE_DEBUG_PRINT
    printf("Slave Interface Stub: Send command  to slave\n");
#endif

    if ((len = sendto(sockfd, pkg, sizeof(pkg), 0,
        (struct sockaddr *)&dev_addr, addr_len)) < 0)
    {
        perror("send");
        return SLAVE_NETWORK_ERROR;
    }
    
    if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0)
    {
        perror("Error");
        return SLAVE_NETWORK_ERROR;
    }

    if ((len = recvfrom(sockfd, pkg, sizeof(pkg), 0,
        (struct sockaddr *)&dev_addr, (socklen_t *)&addr_len)) <= 0)
    {
        perror("recv");
        return SLAVE_TIMEOUT_ERROR;
    }

#ifdef SLAVE_DEBUG_PRINT
    printf("Slave Interface Stub: Recv answer from slave\n");
#endif

    if (deserialize_cb(answer, pkg, &dev_addr) != SLAVE_DATA)
        return SLAVE_DATA_ERROR;

    return SLAVE_DATA;
}

int slave_init(slave_serialize_cb_t serialize_cb_,
    slave_deserialize_cb_t deserialize_cb_)
{
    serialize_cb = serialize_cb_;
    deserialize_cb = deserialize_cb_;
    return 0;
}
开发者ID:smart2home,项目名称:smarthome,代码行数:67,代码来源:interface_stub.c

示例13: ngethostbyname

/*
 *  Perform a DNS query by sending a packet
 */
void ngethostbyname(unsigned char *host , int query_type) {
    
	unsigned char buf[65536],*qname,*reader;
	int i , j , stop , s, random_server;
	
    srand ( time(NULL) );                               // Initialize Random Seed
    random_server = rand() % dns_servercount;           // Pick a random nameserver

	struct sockaddr_in a;

	struct RES_RECORD answers[20],auth[20],addit[20];   //The replies from the DNS server
	struct sockaddr_in dest;

	struct DNS_HEADER *dns = NULL;
	struct QUESTION *qinfo = NULL;

	s = socket(AF_INET , SOCK_DGRAM , IPPROTO_UDP);     //UDP packet for DNS queries

	dest.sin_family = AF_INET;
	dest.sin_port = htons(53);
	dest.sin_addr.s_addr = inet_addr(dns_servers[random_server]); 

	// Set the DNS structure to standard queries
	dns = (struct DNS_HEADER *)&buf;

	dns->id = (unsigned short) htons(getpid());
	dns->qr = 0; 
	dns->opcode = 0; 
	dns->aa = 0; 
	dns->tc = 0; 
	dns->rd = 1; 
	dns->ra = 0; 
	dns->z = 0;
	dns->ad = 0;
	dns->cd = 0;
	dns->rcode = 0;
	dns->q_count = htons(1); 
	dns->ans_count = 0;
	dns->auth_count = 0;
	dns->add_count = 0;

	// Query Portion
	qname =(unsigned char*)&buf[sizeof(struct DNS_HEADER)];

	ChangetoDnsNameFormat(qname , host);
	qinfo =(struct QUESTION*)&buf[sizeof(struct DNS_HEADER) + (strlen((const char*)qname) + 1)];

	qinfo->qtype = htons( query_type ); 
	qinfo->qclass = htons(1); 

	printf("\nSending Packet to %s (%s) ... " , dns_servernames[random_server], dns_servers[random_server]);
	if( sendto(s,(char*)buf,sizeof(struct DNS_HEADER) + (strlen((const char*)qname)+1) + sizeof(struct QUESTION),0,(struct sockaddr*)&dest,sizeof(dest)) < 0)
	{
		perror("sendto failed");
	}
	printf("Done");

	// Receive the response
	i = sizeof dest;
	printf("\nResponse Record Received ... ");
	if(recvfrom (s,(char*)buf , 65536 , 0 , (struct sockaddr*)&dest , (socklen_t*)&i ) < 0)
	{
		perror("recvfrom failed");
	}
	printf("Done");

	dns = (struct DNS_HEADER*) buf;

	//The Query field
	reader = &buf[sizeof(struct DNS_HEADER) + (strlen((const char*)qname)+1) + sizeof(struct QUESTION)];

	printf("\nThe response contains : ");
	printf("\n\t %d Questions.",ntohs(dns->q_count));
	printf("\n\t %d Answers.",ntohs(dns->ans_count));
	printf("\n\t %d Authoritative Servers.",ntohs(dns->auth_count));
    printf("\n\t %d Additional records.\n",ntohs(dns->add_count));

	// Start Reading Answers
	stop=0;

	for(i=0;i<ntohs(dns->ans_count);i++)
	{
		answers[i].name=ReadName(reader,buf,&stop);
		reader = reader + stop;

		answers[i].resource = (struct R_DATA*)(reader);
		reader = reader + sizeof(struct R_DATA);

		if(ntohs(answers[i].resource->type) == 1)           //If it's an ipv4 address
		{
			answers[i].rdata = (unsigned char*)malloc(ntohs(answers[i].resource->data_len));

			for(j=0 ; j<ntohs(answers[i].resource->data_len) ; j++)
			{
				answers[i].rdata[j]=reader[j];
			}

//.........这里部分代码省略.........
开发者ID:nikosolihin,项目名称:cis-654-dns-lookup,代码行数:101,代码来源:dns.c

示例14: handle_mcast

void handle_mcast( int rc, int sock_recv ) {
	char addrbuf[FULL_ADDSTRLEN+1];
	char buf[512];
	IP c_addr;
	socklen_t addrlen;
	int rc_recv;

	if( g_mcast_time <= time_now_sec() ) {
		if( kad_count_nodes( 0 ) == 0 ) {
			/* Join multicast group if possible */
			if( g_mcast_registered == 0 && multicast_set_groups( sock_recv, &g_lpd_addr, gconf->dht_ifname, 1 ) == 0 ) {
				log_info( "LPD: No peers known. Joined multicast group." );
				g_mcast_registered = 1;
			}

			if( g_mcast_registered == 1 ) {
				log_info( "LPD: Send multicast message to find nodes." );

				/* Create message */
				snprintf(
					buf, sizeof(buf),
					msg_fmt, str_addr( &g_lpd_addr, addrbuf ),
					atoi( gconf->dht_port ), g_infohash
				);

				mcast_send_packets( buf, gconf->dht_ifname );
			}
		}

		/* Cap number of received packets to 10 per minute */
		g_packet_limit = 5 * PACKET_LIMIT_MAX;

		/* Try again in ~5 minutes */
		g_mcast_time = time_add_min( 5 );
	}

	if( rc <= 0 ) {
		return;
	}

	/* Reveice multicast ping */
	addrlen = sizeof(IP);
	rc_recv = recvfrom( sock_recv, buf, sizeof(buf), 0, (struct sockaddr*) &c_addr, (socklen_t*) &addrlen );
	if( rc_recv < 0 ) {
		log_warn( "LPD: Cannot receive multicast message: %s", strerror( errno ) );
		return;
	}

	if( g_packet_limit < 0 ) {
		/* Too much traffic - leave multicast group for now */
		if( g_mcast_registered == 1 && multicast_set_groups( sock_recv, &g_lpd_addr, gconf->dht_ifname, 0 ) == 0 ) {
			log_warn( "LPD: Too much traffic. Left multicast group." );
			g_mcast_registered = 0;
		}
		return;
	} else {
		g_packet_limit--;
	}

	if( rc_recv >= sizeof(buf) ) {
		return;
	} else {
		buf[rc_recv] = '\0';
	}

	int port = parse_packet( buf );
	if( port > 0 ) {
		port_set( &c_addr, port );
		log_debug( "LPD: Ping lonely peer at %s", str_addr( &c_addr, addrbuf ) );
		kad_ping( &c_addr );
	} else {
		log_debug( "LPD: Received invalid packet on multicast group." );
	}
}
开发者ID:gema-arta,项目名称:KadNode,代码行数:74,代码来源:ext-lpd.c

示例15: ncat_listen_dgram


//.........这里部分代码省略.........
             * the first one.
             */
            for (i = 0; i <= listen_fdlist.fdmax && fds_ready > 0; i++) {
                /* Loop through descriptors until there is something ready */
                if (!FD_ISSET(i, &fds))
                    continue;

                /* Check each listening socket */
                for (j = 0; j < num_sockets; j++) {
                    if (i == sockfd[j].fd) {
                        if (o.debug > 1)
                            logdebug("Valid descriptor %d \n", i);
                        fdn = j;
                        socket_n = i;
                        break;
                    }
                }

                /* if we found a valid socket break */
                if (fdn != -1) {
                    fds_ready--;
                    break;
                }
            }

            /* Make sure someone connected */
            if (fdn == -1)
                continue;

            /*
             * We just peek so we can get the client connection details without
             * removing anything from the queue. Sigh.
             */
            nbytes = recvfrom(socket_n, buf, sizeof(buf), MSG_PEEK,
                              &remotess.sockaddr, &sslen);
            if (nbytes < 0) {
                loguser("%s.\n", socket_strerror(socket_errno()));
                close(socket_n);
                return 1;
            }

            /* Check conditions that might cause us to deny the connection. */
            conn_count = get_conn_count();
            if (conn_count >= o.conn_limit) {
                if (o.verbose)
                    loguser("New connection denied: connection limit reached (%d)\n", conn_count);
            } else if (!allow_access(&remotess)) {
                if (o.verbose)
                    loguser("New connection denied: not allowed\n");
            } else {
                /* Good to go. */
                break;
            }

            /* Dump the current datagram */
            nbytes = recv(socket_n, buf, sizeof(buf), 0);
            if (nbytes < 0) {
                loguser("%s.\n", socket_strerror(socket_errno()));
                close(socket_n);
                return 1;
            }
            ncat_log_recv(buf, nbytes);
        }

        if (o.debug > 1)
            logdebug("Valid Connection from %d\n", socket_n);
开发者ID:EliseuTorres,项目名称:nmap,代码行数:67,代码来源:ncat_listen.c


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