I do apologize if this question has been asked before. I am writing a non-blocking socket client using select multiplexing. One thing that confuses me is the non-blocking connect always succeeds regardless of server being online or offline. I searched many posts and followed their solutions but none of them work on my linux ubuntu machine.
static void callback_on_select_write(int connect_fd) {
// Client write event arrived;
int error = -1;
socklen_t len = sizeof(error);
if(getsockopt(connect_fd, SOL_SOCKET, SO_ERROR, &error, &len) == -1) {
return;
}
// getsockopt puts the errno value for connect into erro so 0 means no-error.
if(error == 0) {
// Connection ok.
}
else {
cerr << "Failed to connect\n";
return;
}
// Ready to write/read
}
Everytime the select returns and invokes this callback which always succeeds, i.e., going to the "Ready to write/read" block, instead of cerring failure. Why can this happen? How do I design a portable mechanism to detect if the connection is really successful? Below is the way I create the connector.
int make_socket_client(const ::std::string& hostname, const ::std::string& port) {
struct addrinfo hints;
struct addrinfo* res {nullptr};
struct addrinfo* ptr {nullptr};
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
int rv;
int connector;
if((rv = getaddrinfo(hostname.c_str(), port.c_str(), &hints, &res)) != 0) {
return -1;
}
// Try to get the first available client connection.
for(ptr = res; ptr != nullptr; ptr = ptr->ai_next) {
// Ignore undefined ip type.
if(ptr->ai_family != AF_INET && ptr->ai_family != AF_INET6) {
continue;
}
// Create a listener socket and bind it to the localhost as the server.
if((connector = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol)) == -1){
continue;
}
make_fd_nonblocking(connector);
if(connect(connector, (struct sockaddr*)ptr->ai_addr, ptr->ai_addrlen) < 0) {
// This is what we expect.
if(errno == EINPROGRESS) {
break;
}
else {
close(connector);
continue;
}
}
else {
break;
}
}
freeaddrinfo(res);
if(ptr == nullptr) {
return -1;
}
return connector;
}