简体   繁体   English

如何在C ++中设置登录超时?

[英]How to set a timeout for a login in C++?

I'm writing a timeout for a simple login on a server written in C++. 我正在为使用C ++编写的服务器上的简单登录编写超时。 Well, this is the code: 好的,这是代码:

char username[this->BUFSIZE];
    clean(username);
    char password[this->BUFSIZE];
    clean(password);
    send(client_fd, "USER", 4, 0);

    //Start timer
    time_t end,start;
    double dif;
    time (&start);

    recv(client_fd,username,BUFSIZE,0);
    send(client_fd, "PASS", 4, 0);
    recv(client_fd,password,BUFSIZE,0);

    //End timer
    time (&end);
    dif = difftime (end,start);
            //If dif>10 seconds disconnect the client.
    if(dif>10)
        close(client_fd);

Ok it works fine, but there is just a problem: the disconnect happens only when the client end typing user + password. 好吧它工作正常,但只有一个问题:只有当客户端输入用户+密码时才会发生断开连接。 My goal is that the timer must close the connection at 10 seconds, independently if the client did the login or not. 我的目标是计时器必须在10秒内关闭连接,如果客户端是否登录则独立。

Is it possible? 可能吗? Thank you! 谢谢!

You can use select() to wait for data on client_fd . 您可以使用select()等待client_fd数据。 select supports a timeout value and will return 0 if the timeout occurs. select支持超时值,如果发生超时,则将返回0 If data is ready, select will return the number of descriptors with data pending. 如果数据准备就绪,则select将返回具有待处理数据的描述符数。

You can also set the socket option SO_RCVTIMEO with a timeval structure. 您还可以使用timeval结构设置套接字选项SO_RCVTIMEO This will cause recv to return once the timeout has happened. 一旦超时发生,这将导致recv返回。

Use a signal - SIGALRM, set this before entering recv and when it triggers close the connection. 使用信号 - SIGALRM,在进入recv之前设置此信号并在触发时关闭连接。

Alternatively use a full-fat framework such as asio, which will provide timers etc. 或者使用asio这样的全脂框架,它将提供定时器等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM