UDP超时处理

#include < stdio.h >
#include
< stdlib.h >
#include
< sys / time.h >
#include
< sys / types.h >
#include
< unistd.h >
#include
< sys / types.h >
#include
< sys / socket.h >
#include
< string .h >
#include
< netinet / in .h >


#define MAXLINE 80
#define SERV_PORT 2514

int
main(
char * agrv[], int argc)
... {
   
int sockfd;
   
struct sockaddr_in servaddr, cliaddr;

    sockfd
= socket(AF_INET, SOCK_DGRAM, 0); /**//* create a socket */

   
/**//* init servaddr */
    bzero(
&servaddr, sizeof(servaddr));
    servaddr.sin_family
= AF_INET;
    servaddr.sin_addr.s_addr
= htonl(INADDR_ANY);
    servaddr.sin_port
= htons(SERV_PORT);

   
/**//* bind address and port to socket */
   
if(bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1)
   
...{
        perror(
"bind error");
        exit(
1);
    }


    fd_set rfds;
   
struct timeval tv;
   
int retval;

   
/**//* Watch stdin (fd 0) to see when it has input. */

    FD_ZERO(
&rfds);
    FD_SET(sockfd,
&rfds);

   
/**//* Wait up to five seconds. */
    tv.tv_sec
= 5;
    tv.tv_usec
= 0;

    retval
= select(sockfd + 1, &rfds, NULL, NULL, &tv);
   
/**//* Don't rely on the value of tv now! */

    socklen_t len;
   
char mesg[1024];
   
struct sockaddr *pcliaddr;

   
if (retval == -1)
        perror(
"select()");
   
else if (retval)
   
...{
        printf(
"Data is available now. ");
        recvfrom(sockfd, mesg,
1024, 0, pcliaddr, &len);
        printf(
"%s ", mesg);
    }

   
else
        printf(
"No data within five seconds. ");

    close(sockfd);

   
return 0;
}

你可能感兴趣的:(socket,struct,null,UP,include)