Timeout implementation in C for TFTP

对着背影说爱祢 提交于 2019-12-07 15:59:09

问题


I am trying to implement the the timeout mechanism in my c implementation of TFTP, and i am looking for some general help.

What I am wondering is how to manage the timeout situation. The premature timeout mechanism that I used is with signal/alarm functions, but somehow I am stuck in how to handle my timeouts, that is if the packet (ack or data) is missed and a timeout occurs how to send back the previous packet or ack to the server.


回答1:


Avoid signal and alarm if possible.

Either use SO_RCVTIMEO socket option or just use select with a timeout of T seconds.

If the select() call returns and your socket is not in the read set, or if recvfrom returns with a timeout error, then you can take appropriately action in your code.

Example of timeout usage:

timeval tv = {0,0};
tv.tv_sec = 5;
socklen_t optionlength = sizeof(tv);
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, optionlength);

while (1)
{
    result = recvfrom(s, buffer, bufferlength, 0);
    if (result == -1) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)) )
    {
       // handle timeout
    }
    else if (result == -1)
    {
       // handle critical error
    }
    else
    {
       // process next packet
    }
}

Example of select usage:

while (1)
{
    timeval tv = {0,0};
    tv.tv_sec = 5;
    fd_set readset = {};
    FD_ZERO(&readset);
    FD_SET(s, &readset);

    select(s+1, &readset, NULL, NULL, &tv);

    if (FD_ISSET(s, &readset))
    {
        result = recvfrom(s, buffer, bufferlength, 0);
        if (result == -1)
        {
            // handle error
        }
        else
        {
            // process packet
        }
    }
    else
    {
       // handle timeout
    }

}


来源:https://stackoverflow.com/questions/16501741/timeout-implementation-in-c-for-tftp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!