linux:
struct timeval timeout={3,0};//3s
int ret=setsockopt(sock_fd,SOL_SOCKET,SO_SNDTIMEO,&timeout,sizeof(timeout));
int ret=setsockopt(sock_fd,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout));
如果ret==0 则为成功,-1为失败,这时可以查看errno来判断失败原因
int recvd=recv(sock_fd,buf,1024,0);
if(recvd==-1&&errno==EAGAIN)
{
printf("timeout\n");
}
windows:
int timeout = 3000; //3s
int ret=setsockopt(sock_fd,SOL_SOCKET,SO_SNDTIMEO,&timeout,sizeof(timeout));
int ret=setsockopt(sock_fd,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout));