int iRecvSize = recvfrom(sockfd, recv_buffer, 1024, 0, (struct sockaddr*)&from,  &fromlen);
        
////////////////////////////////////////////////
fprintf(stdout, "Function recvfrom return value=%d\r\n", iRecvSize);
if (iRecvSize == SOCKET_ERROR)
{
fprintf(stdout, "Cannot get ICMP reply\r\n");
exit(-1);
}
//////////////////////////////程序执行到iRecvSize = recvfrom(……),如果对方的机器开机,则不会执行下面的
if (iRecvSize == SOCKET_ERROR)判断,
但是如果对方的机器关机,则程序死在iRecvSize = recvfrom(……),不去判断if (iRecvSize == SOCKET_ERROR),请问怎么会事?如何在对方没有开机的情况下让recvfrom函数能返回SOCKET_ERROR?

解决方案 »

  1.   

    socket阻塞了,用select函数设置超时时间
      

  2.   

    程序执行到iRecvSize = recvfrom(……),如果对方的机器开机,则不会执行下面的
    if (iRecvSize == SOCKET_ERROR)判断,msdn的说明
    If no incoming data is available at the socket, the recvfrom function blocks and waits for data to arrive according to the blocking rules defined for WSARecv with the MSG_PARTIAL flag not set unless the socket is nonblocking. In this case, a value of SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK. The select, WSAAsyncSelect, or WSAEventSelect can be used to determine when more data arrives.If the socket is connection oriented and the remote side has shut down the connection gracefully, the call to recvfrom will complete immediately with zero bytes received. If the connection has been reset recvfrom will fail with the error WSAECONNRESET.