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

前端 未结 6 2271
难免孤独
难免孤独 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:13

    This is little bit off topic, but I really want to share this solution to set recv timeout both on windows and unix. Maybe it's me, but it took me a lot of time to figure out why my program doesn't work and how to properly set timeout. Hope you find it useful. It sets timeout to 10 seconds.

    For Windows:

    DWORD sock_timeout = 10*1000;
    

    For Unix:

    const struct timeval sock_timeout={.tv_sec=10, .tv_usec=0};
    

    For both:

    setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&sock_timeout, sizeof(sock_timeout));
    

提交回复
热议问题