0

我将超时设置为recvfrom(). 我在 Cygwin64 环境下运行我的代码。

.his 是我的代码示例:

if(( clientSock=socket(AF_INET, SOCK_DGRAM,0))==-1){ // creat client socket 
    perror("Socket Initialisation Error\n");
}//if

struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
if (setsockopt(clientSock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof tv)) {
    perror("setsockopt");    
}

memset(&client,0, sizeof(client)); // clear the memory of 
client addrinfo

client.sin_port=htons(clientPort);// asign client port
client.sin_family=AF_INET; // ipv4
client.sin_addr.s_addr=INADDR_ANY;
bzero(&client.sin_zero,8);

if((bind(clientSock,(struct sockaddr*)&client, sizeof(struct sockaddr_in)))==-1){ // bind socket with addrinfo
    perror("\n Bind: ");
} 

server.sin_family=AF_INET; // server ipv4 type
server.sin_port=htons(serverPort); // assign server port
server.sin_addr.s_addr=inet_addr(serverIp); // asign server ip
bzero(&server.sin_zero,8);

while(1){
    // send to the server is ok then  wait for receive: 

    if((recvfrom(clientSock,&rcvPkt,sizeof(struct packet),0,(struct sockaddr *)&server,&sockLength))<0){ // wait for receiving replay from server 
        puts("\nerror in receiving CONF packet");
    }
    sleep(1);
}

程序一直在等待recvfrom():超时不起作用。

4

0 回答 0