首先我想说这是另一个问题:相似但不一样
我的代码如下所示:
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 地址存在,但没有服务器在我尝试连接的端口上侦听)。
选择总是返回 1。为什么?根据 man 它应该超时并返回 0。在此之后,当我尝试向套接字写入内容时,它返回 -1/ECONNREFUSED。
这是预期的行为吗?如果是,如何在 select() 之后检查我们是否已连接?