C语言socket设置超时/setsockopt函数

2/22/2017来源:ASP.NET技巧人气:2957

//======================= 在Windows下似乎操作比较简单,直接调用winsock2.h和ws2_32.lib编程 #include"stdafx.h" #include"stdio.h" #include "winsock2.h" #PRagmacomment(lib, "ws2_32.lib")   设置接收超时为 nNetTimeout 可采用如下方法: int nNetTimeout= 2000ms; if (SOCKET_ERROR ==  setsockopt(serSocket,SOL_SOCKET, SO_RCVTIMEO, (char *)&nNetTimeout,sizeof(int)))             printf("Set Ser_RecTIMEO error !\r\n");    int ret = recvfrom(serSocket, recvData, 255, 0, (sockaddr*)&remoteAddr, &nAddrLen);       if(ret<0)     {          printf("recv timeout! %d\n",ret);//ret = -1          //continue;      } 设置接收超时成功后,若超时,返回值为ret =  -1 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>linux<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< 而Linux下则不太一样,timeout若仍采用int型将没有效果。 linux下应将timeout类型改成struct timeval! 注意符号: struct timevaltimeout={4,0}; //即timeout={4,0};或者timeout.tv_sec=4; timeout.tv_usec=0; //设置接收超时 //setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,sizeof(timeout)); setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,sizeof(structtimeval)); //同样接收超时后接收返回-1 if((rec_length=recvfrom(sockfd,recbuf,MAXDATASIZE,0,(structsockaddr *)&peer,&addrlen))== -1){     printf("recvtimeout!\n"); } //======================