我有一个非常简单的 TCP 客户端,如下所示。问题是connect()
即使对方没有服务器,调用也总是返回 0。
int TcpSend(struct sockaddr_in* ipv4_client, const void* buffer, size_t size) {
int sd_client = 0;
int status = -1;
// Grab an ipv4 TCP socket.
sd_client = socket(AF_INET, SOCK_STREAM, 0);
if (sd_client == -1) {
return -1;
}
// Make the socket non-blocking so that connect may fail immediately
status = fcntl(sd_client, F_SETFL, O_NONBLOCK);
if (status < 0) {
close(sd_client);
return -1;
}
// Bind and connect
status = connect(sd_client, (struct sockaddr*)ipv4_client, sizeof(*ipv4_client));
if (status == -1) {
close(sd_client);
return -1;
}
printf("Status: %d %s\n", status, strerror(errno)); //// ??? : I always get status = 0 here
// Send a message to the server PORT on machine HOST.
// Ignore the fact that send might not have sent the complete data
status = send(sd_client, buffer, size, 0); //// Consequently I get a SIGPIPE here
if (status == -1) {
close(sd_client);
return -1;
}
close(sd_client);
return 0;
}
我知道connect()
如果只是绑定成功并且连接没有发生,那将会通过。但是,它不应该在制作套接字时发生O_NONBLOCK
。代码总是通过,connect()
我在里面得到一个SIGPIPE
错误send()
。