I want to create a socket in Android with NDK, but sometimes I get some errors when connecting to server, and I can make sure that the network of the users' cell phone is available.
One case is timeout error, and the other seems like connect refused, because I get the following logs, I think the second error is connect refused because the error from getsockopt
is 111 even though the strerror
give me Operation now in progress, but the server address is valid:
connect::socket error: Operation now in progress
Or
connect::error:111, Operation now in progress
Here is my code snippet:
bool connect(int sockfd, struct sockaddr *address, socklen_t address_len, int timeout) {
int ret = 0;
struct timeval tv;
fd_set mask;
// set socket non block
int flags = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
// use select to check socket connection
ret = connect(sockfd, address, address_len);
if (-1 == ret) {
if (errno != EINPROGRESS) {
perror("connect");
inetConnectFailCode = errno;
LOG(TAG.c_str(), "connect::errno != EINPROGRESS: %s", strerror(errno));
return false;
}
LOG(TAG.c_str(), "connecting...\n");
FD_ZERO(&mask);
FD_SET(sockfd, &mask);
tv.tv_sec = timeout;
tv.tv_usec = 0;
if (select(sockfd + 1, NULL, &mask, NULL, &tv) > 0) {
int error = 0;
socklen_t tmpLen = sizeof(int);
int retopt = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &tmpLen);
if (retopt != -1) {
if (0 == error) {
LOG(TAG.c_str(), "has connect");
return true;
} else {
//I get error here
LOG(TAG.c_str(), "connect::error:%d, %s", error, strerror(errno));
return false;
}
} else {
LOG(TAG.c_str(), "connect::socket error:%d", error);
return false;
}
} else {
//timeout, and I get error here sometimes
LOG(TAG.c_str(), "connect::socket error: %s", strerror(errno));
return false;
}
}
LOG(TAG.c_str(), "has connect");
return true;
}
This problem has been bothering me for a long time, anybody can give me a favor, thanks for advance.