本文介绍了非阻塞套接字select返回后1连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先我想说,这是另一个问题不止这一个:Similar但不一样的

First of all I would like to say that this is another problem than this one: Similar but not the same

我的code是这样的:

My code looks like this:

struct addrinfo hints, *res;
struct sockaddr* serveraddr;

memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;

int res2 = getaddrinfo(ip, port, &hints, &res);
printf("getaddrinfo() res: %d, %d\n", res2, errno);

serveraddr = res->ai_addr;

//create new socket

int soc = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
printf("socket() res: %d, %d\n", socket, errno);

//set nonblocking mode
unsigned long on = 1;
res2 = ioctl(soc, FIONBIO, &on);
printf("ioctl() res: %d\n, %d", res2, errno);

res2 = connect(soc, serveraddr, sizeof(struct sockaddr));
printf("connect() res: %d, %d\n", res2, errno);

//check if socket is ready
fd_set wfds;
FD_ZERO(&wfds);
FD_SET(soc, &wfds);

struct timeval t;
t.tv_sec=15;
t.tv_usec=0;

res2 = select(soc + 1, 0, &wfds, 0, &t);
printf("select() res: %d, %d\n", res2, errno);`

我连接到存在(IP地址存在,但是没有服务器侦听端口,我试图连接)。

I'm connecting to machine that exists (IP address exists, but there is no server listening on port I'm trying to connect).

选择总是返回1.为什么?据人应该超时并返回0。
在此之后,当我尝试写一些东西到插座返回-1 / ECONNREFUSED。

Select always returns 1. Why? According to man it should timeout and return 0.After this when I try to write something to socket it returns -1/ECONNREFUSED.

这是预期的行为?如果有,如何选择()是我们连接后检查?

Is this expected behaviour? If yes, how to check after select() is we are connected?

推荐答案

我不知道在哪里的man页面可以看到,它应该超时。

I don't know where in the man pages you see that it should time out.

如果没有防火墙丢弃的数据包,连接将被拒绝pretty快(从主机中一个包,一个包的回复)。因此,一个事件的连接插座将尽快复位接收进来了。这将唤醒选择,用(至少)一个活动的套接字。

If there is no firewall dropping the packets, the connection will be refused pretty fast (one packet from your host, one packet reply). So an "event" on the connecting socket will come in as soon as the reset is received. This will wake up select, with (at least) one active socket.

读取或写入该插座的第一次尝试将返回底层连接错误。

The first attempt to read from or write to that socket will return the underlying connect error.

这篇关于非阻塞套接字select返回后1连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 19:00