Socket with recv-timeout: What is wrong with this code?

前端 未结 6 2270
难免孤独
难免孤独 2021-02-20 16:41

I\'m trying to implement a socket with a recv timeout of 1 Second:

int sockfd;
struct sockaddr_in self;
struct sockaddr_in client_addr;
int addrlen=sizeof(clien         


        
6条回答
  •  逝去的感伤
    2021-02-20 17:10

    Here's a snippet using select:

    FD_ZERO(&masterfds);
    FD_SET(sockfd,&masterfds);
    memcpy(&readfds,&masterfds,sizeof(fd_set));
    timeout.tv_sec = 2;
    timeout.tv_usec = 0;
    if (select(sockfd+1, &readfds, NULL, NULL, &timeout) < 0)
    {
        printf("select error");
        exit(1);
    }
    
    if (FD_ISSET(sockfd, &readfds))
    {
        //printf("Read from socket\n");
        // read from the socket
        res = recvfrom(sockfd, (char *)hdrbuf, sizeof(hdrbuf), MSG_PEEK, recvaddr, address_len);
    }
    else
    {
        // the socket timedout
        //printf("Socket timeout started=%d\n",packets_started);
    

提交回复
热议问题