C语言socket编程设置接收超时(Window&Linux)

最近在用C写socket时,发现要对udp接收的时间进行监听,不然使用阻塞接收时将会造成一直等待。

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Windows<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
在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型将没有效果。
参考 http://blog.csdn.net/newger/article/details/2459113
一文后发现,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");
}
     

你可能感兴趣的:(C/Cplus,CC++,socket,udp,网络编程,linux)