连接失败后如何清理套接字?

时间:2013-05-16 23:06:40

标签: c++ sockets

代码如下。我创建一个TCP套接字并尝试连接。连接失败。但是,缓冲区中存在某些内容,并且套接字仍然可读。在这种情况下有没有办法清理插座?非常感谢您的帮助。

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/inotify.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#include <sys/select.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/epoll.h>
#include <signal.h>
#include <math.h>
#include <netdb.h>
#include <errno.h>


int main()
{
    int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    struct sockaddr_in sai;
    sai.sin_family = AF_INET;
    int rv = inet_pton(AF_INET, "10.10.131.1", &(sai.sin_addr));
    sai.sin_port = htons(1234);

    int r = connect(sock, (struct sockaddr*)(&sai), sizeof(struct sockaddr_in));
    if (r < 0)
    {
        printf("connection failed: %s\n", strerror(errno));
    }


    fd_set r_set;
    FD_ZERO(&r_set);
    FD_SET(sock, &r_set);

    int n = select(sock + 1, &r_set, NULL, NULL, NULL);

    if (n > 0)
    {
        if (FD_ISSET(sock, &r_set))
        {
            printf("socket %d is readable\n", sock);
        }
    }

    return 0;
}

执行结果:

connection failed: Connection refused
socket 3 is readable

1 个答案:

答案 0 :(得分:3)

缓冲区中没有任何内容。 “可读”意味着您在套接字上有一些事件,此时您已经知道 - 连接尝试失败。在这里使用select(2)并没有必要清理任何东西。