我有一个非常简单的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()
错误。
答案 0 :(得分:2)
在非阻塞模式下连接后,你需要在可写集合中调用带有套接字FD的select(),即等到它变为可写,然后(1)通过{{1}检查套接字上的错误}或(2)再次调用connect()并检查错误。只有这样才能开始调用getsockopt(),
或send()
答案 1 :(得分:2)
问题是ipv4_client->sin_family
不知何故为0。
执行以下操作可以解决问题。
ipv4_client->sin_family = AF_INET;