I'm using this code to connect to a server, but it is not waiting the 10 seconds I set to timeout. It returns immediately after failing to connect.
BOOL Connect(string server, int port, int timeout)
{
struct sockaddr_in RemoteHost;
TIMEVAL Timeout;
Timeout.tv_sec = timeout;
Timeout.tv_usec = 0;
int con_error = 0;
#ifdef W32
WSADATA wsd;
if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
{
DEBUG(L"Failed to load Winsock!\n");
return FALSE;
}
#endif
//create socket if it is not already created
if (s == SOCKET_ERROR)
{
//Create socket
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == SOCKET_ERROR)
{
DEBUG(L"Could not create socket");
return FALSE;
}
}
//setup address structure
if (inet_addr(server.c_str()) == INADDR_NONE)
{
struct hostent *he;
//resolve the hostname, its not an ip address
if ((he = gethostbyname(server.c_str())) == NULL)
{
//gethostbyname failed
DEBUG(L"gethostbyname() - Failed to resolve hostname\n");
return FALSE;
}
}
else//plain ip address
{
RemoteHost.sin_addr.s_addr = inet_addr(server.c_str());
}
RemoteHost.sin_family = AF_INET;
RemoteHost.sin_port = htons(port);
//set the socket in non-blocking
unsigned long iMode = 1;
int iResult = ioctlsocket(s, FIONBIO, &iMode);
if (iResult != NO_ERROR)
{
DEBUGP(L"ioctlsocket failed with error: %ld\n", iResult);
return FALSE;
}
//Connect to remote server
if ((con_error=connect(s, (struct sockaddr *)&RemoteHost, sizeof(RemoteHost))) < 0)
{
if (con_error != EINPROGRESS)
{
DEBUG(L"connect() failed");
return FALSE;
}
}
// restart the socket mode
iMode = 0;
iResult = ioctlsocket(s, FIONBIO, &iMode);
if (iResult != NO_ERROR)
{
DEBUGP(L"ioctlsocket failed with error: %ld\n", iResult);
return FALSE;
}
fd_set Write, Err;
FD_ZERO(&Write);
FD_ZERO(&Err);
FD_SET(s, &Write);
FD_SET(s, &Err);
// check if the socket is ready
select(0, NULL, &Write, &Err, &Timeout);
if (FD_ISSET(s, &Write))
{
return TRUE;
}
return FALSE;
}
When the socket is not available on the target system, it may send back an ICMP message indicating that the socket is not open and attempt to connect was failed. In this case, winsock funcitons will return immediately - it's by design.
Use WSAGetLastError to find out why the call has failed. connect returns 0 on success or SOCKET_ERROR on failure.
You commented that WSAGetLastError returns WSAEWOULDBLOCK which states:
This error is returned from operations on nonblocking sockets that cannot be completed immediately, for example recv when no data is queued to be read from the socket. It is a nonfatal error, and the operation should be retried later. It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a nonblocking SOCK_STREAM socket, since some time must elapse for the connection to be established.
So is expected behaviour on the non-blocking socket you have set up.
Related
I have a thread that accepts client connections and makes the client sockets non blocking.
for(char Index = 0; Index < MAX_CLIENTS; ++Index)
{
if(ClientSockets[Index] == INVALID_SOCKET)
{
accept(ClientSockets[Index], (sockaddr *)&Address, &AddressSize);
unsigned long iMode = 1;
if(ioctlsocket(ClientSockets[Index], FIONBIO, &iMode) != NO_ERROR)
{
Error("Making client socket unblocking has failed.\n");
}
}
}
In the main thread I receieve packets from the clients.
In the main thread after I execute Sleep() the program returns 1 and ends.
The only thing that I found to work was removing ioctlsocket from the thread that accepts clients.
You are using accept() incorrectly.
The 1st parameter of accept() is an input-only parameter, specifying which listening socket to accept a pending client connection for. That parameter is not an output parameter, like you are trying to treat it as.
You are passing ClientSockets[Index] to the 1st parameter accept(). But ClientSockets[Index] is set to INVALID_SOCKET. That will make accept() fail, but you are ignoring that error. You need to pass in the listening socket that you created earlier with socket() instead.
You are not assigning the return value of accept() to ClientSockets[Index], so it remains set to INVALID_SOCKET. You are then passing that to the 1st parameter of ioctlsocket(), which will fail. You do check that error, but you are not reporting WHY it failed, otherwise you would have known that it is failing with an error code of WSAENOTSOCK (10038) due to being passed an invalid socket.
Try something more like this instead:
for(char Index = 0; Index < MAX_CLIENTS; ++Index)
{
if (ClientSockets[Index] == INVALID_SOCKET)
{
AddressSize = sizeof(Address);
ClientSockets[Index] = accept(serverSocket, (sockaddr *)&Address, &AddressSize);
if (ClientSockets[Index] != INVALID_SOCKET)
{
unsigned long iMode = 1;
if (ioctlsocket(ClientSockets[Index], FIONBIO, &iMode) != SOCKET_ERROR)
{
Error("Making client socket unblocking has failed.\n");
closesocket(ClientSockets[Index]);
ClientSockets[Index] = INVALID_SOCKET;
continue;
}
// use ClientSockets[Index] as needed ...
}
}
}
Alternatively:
AddressSize = sizeof(Address);
SOCKET clientSocket = accept(serverSocket, (sockaddr *)&Address, &AddressSize);
if (clientSocket != INVALID_SOCKET)
{
unsigned long iMode = 1;
if (ioctlsocket(clientSocket, FIONBIO, &iMode) != SOCKET_ERROR)
{
Error("Making client socket unblocking has failed.\n");
closesocket(clientSocket);
}
else
{
int Index;
for(Index = 0; Index < MAX_CLIENTS; ++Index)
{
if (ClientSockets[Index] == INVALID_SOCKET)
break;
}
if (Index == MAX_CLIENTS)
{
Error("No room for client socket.\n");
closesocket(clientSocket);
}
else
{
ClientSockets[Index] = clientSocket;
// use clientSocket as needed ...
}
}
}
I'm using VC++ on Visual Studio 2010.
Now I've got some problem. I think it's so silly question but I want to get a clear answer.
How can I get CLOSE_WAIT state of an selected SOCKET?
// SocketThreadConn.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <WinSock.h>
#include <Windows.h>
#pragma comment(lib, "ws2_32.lib")
#define PR_RECORED_TIME 10*1000 // (ms)
BYTE* pByteCamData = NULL;
INT nHeight = 900;
INT nWidth = 1600;
INT nSpect = 3;
INT nSolution = nHeight * nWidth * nSpect;
VOID SendRecoredData(SOCKET socket2operation);
int _tmain(int argc, _TCHAR* argv[])
{
pByteCamData = new BYTE[nSolution]; // <-- use [], not ()!
//----------------------
// Initialize Winsock.
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup failed with error: %d\n", iResult);
delete[] pByteCamData;
return 1;
}
//----------------------
// Create a SOCKET for listening for
// incoming connection requests.
SOCKET ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
wprintf(L"socket failed with error: %d\n", WSAGetLastError());
WSACleanup();
delete[] pByteCamData;
return 1;
}
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is being bound.
sockaddr_in service = {};
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY; // inet_addr("127.0.0.1");
service.sin_port = htons(27015);
if (bind(ListenSocket, (SOCKADDR *) &service, sizeof(service)) == SOCKET_ERROR) {
wprintf(L"bind failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
delete[] pByteCamData;
return 1;
}
//----------------------
// Listen for incoming connection requests.
// on the created socket
if (listen(ListenSocket, 1) == SOCKET_ERROR) {
wprintf(L"listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
delete[] pByteCamData;
return 1;
}
//----------------------
// Accept the connection.
wprintf(L"Waiting for client to connect...\n");
SOCKET AcceptSocket = accept(ListenSocket, NULL, NULL);
if (AcceptSocket == INVALID_SOCKET) {
wprintf(L"accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
delete[] pByteCamData;
return 1;
}
wprintf(L"Client connected.\n");
SendRecoredData(AcceptSocket); // <-- logic fix!
// No longer need client socket
closesocket(AcceptSocket); // <-- CLOSE_WAIT fix!
// No longer need server socket
closesocket(ListenSocket);
WSACleanup();
delete[] pByteCamData;
return 0;
}
VOID SendRecoredData(SOCKET socket2operation)
{
if(IsSocketAlive(socket2operation) == 0)
return;
INT nCountDown = 5;
INT nSentData, nNumToSend;
BYTE *pData;
do
{
if (nCountDown == 0)
{
nCountDown = 5;
pData = pByteCamData;
nNumToSend = nSolution;
while (nNumToSend > 0) <-- send() fix!
{
nSentData = send(socket2operation, (char*)pData, nNumToSend, 0);
if (SOCKET_ERROR == nSentData) {
wprintf(L"send failed with error: %d\n", WSAGetLastError());
return;
}
pData += nSentData;
nNumToSend -= nSentData;
}
wprintf(L"Sent Camera Data OK [%d] Bytes\n", nSolution);
}
Sleep(PR_RECORED_TIME);
--nCountDown;
}
while (TRUE);
}
INT IsSocketAlive(SOCKET socket2check)
{
if (socket2check == INVALID_SOCKET)
return FALSE;
INT nError_code = -1;
INT nError_code_size = sizeof(nError_code);
INT nRetValue = getsockopt(socket2check, SOL_SOCKET, SO_ERROR, (CHAR*)&nError_code, &nError_code_size);
// if (nRetValue != -1)
{
// _tprintf(_T("Error getting socket error code : %d \n"), strerror(nRetValue));
}
if (nError_code != 0)
{
_tprintf(_T("Socket error : %d \n"), strerror(nError_code));
}
switch (nError_code)
{
case 0:
return TRUE;
break;
case SOCKET_ERROR:
return FALSE;
default:
return FALSE;
}
}
A problem is CLOSE_WAIT 'ed' socket is checked as alive socket.
When SocketThreadConn.exe is working on while loop, it doesn't break loop though Listen socket is CLOSE_WAIT.
How can I check accepted socket is ESTABLISHED?
(This code has changed by #Remy Lebeau)
How can I check is a socket is still ESTABLISHED not using send() or GetTcpTable().
Function GetTcpTable() is working well but I have to find socket only using their value(USHORT). There is no field for socket value in MIB_TCPTABLE.
#define SOCKET_ALIVE 10
#define SOCKET_DEAD 9
INT CheckSocketAlive(SOCKET socket2check)
{
fd_set fdR;
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
FD_ZERO(&fdR);
FD_SET(socket2check, &fdR);
switch (select(socket2check + 1, &fdR, NULL,NULL, &timeout))
{
case SOCKET_ERROR:
_tprintf(_T("\tError condition. Code : [%d]\n"), WSAGetLastError());
return SOCKET_DEAD;
case 0:
return SOCKET_ALIVE;
default:
if ( FD_ISSET(socket2check, &fdR) )
{
_tprintf(_T("A read event has occurred on socket [socket2check].\n"));
return SOCKET_DEAD;
}
break;
}
}
You can get state of selected socket using this function.
But only SOCKET_ERROR or SOCKET_ALIVE.
You can change timeout.tv_sec (1sec) as you want.
How can I get CLOSE_WAIT state of an selected SOCKET?
There is no Winsock API for that particular purpose. However, you can retrieve the SOCKET's two IP/port pairs (via getsockname() and getpeername()) and then look for them in the output of GetTcpTable() or related function. That will give you the current state, and even the owning process.
But, there is a bug in your code that is causing the CLOSE_WAIT state - you are not closing the SOCKET returned by accept(). CLOSE_WAIT means an established connection received a FIN from the other peer, and is waiting for you to send a FIN and close your SOCKET handle for the connection.
Fix that bug, and you won't need to resort to using GetTcpTable() at all.
How can I check accepted socket is ESTABLISHED?
You could use GetTcpTable() for that as well. However, the best way is to just perform actual I/O over the connection and see if it succeeds or fails. Your IsSocketAlive() function is incorrect and useless as-is. Use the return value from send() to know if the socket is still alive (since you are not reading any data from the client).
With that said, there are other bugs in your code, too.
You are not allocating pByteCamData correctly. You need to use [] instead of (). You are allocating a single BYTE with nSolution as its value, not an array of nSolution number of bytes.
You are passing the listening SOCKET to SendRecoredData(), but you should be passing the SOCKET from accept() instead.
send() is not guaranteed to send all of the requested bytes in a single go. It can send fewer bytes than requested (which is likely since you are trying to send > 4MB at a time). If the return value is less than the number of bytes requested, you have to call send() again to send the remaining bytes. So, call send() in a loop until there are no more bytes to send.
Try something more like this:
// SocketThreadConn.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <WinSock.h>
#include <Windows.h>
#pragma comment(lib, "ws2_32.lib")
#define PR_RECORED_TIME 10*1000 // (ms)
BYTE* pByteCamData = NULL;
INT nHeight = 900;
INT nWidth = 1600;
INT nSpect = 3;
INT nSolution = nHeight * nWidth * nSpect;
VOID SendRecoredData(SOCKET socket2operation);
int _tmain(int argc, _TCHAR* argv[])
{
pByteCamData = new BYTE[nSolution]; // <-- use [], not ()!
//----------------------
// Initialize Winsock.
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup failed with error: %d\n", iResult);
delete[] pByteCamData;
return 1;
}
//----------------------
// Create a SOCKET for listening for
// incoming connection requests.
SOCKET ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
wprintf(L"socket failed with error: %d\n", WSAGetLastError());
WSACleanup();
delete[] pByteCamData;
return 1;
}
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is being bound.
sockaddr_in service = {};
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY; // inet_addr("127.0.0.1");
service.sin_port = htons(27015);
if (bind(ListenSocket, (SOCKADDR *) &service, sizeof(service)) == SOCKET_ERROR) {
wprintf(L"bind failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
delete[] pByteCamData;
return 1;
}
//----------------------
// Listen for incoming connection requests.
// on the created socket
if (listen(ListenSocket, 1) == SOCKET_ERROR) {
wprintf(L"listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
delete[] pByteCamData;
return 1;
}
//----------------------
// Accept the connection.
wprintf(L"Waiting for client to connect...\n");
SOCKET AcceptSocket = accept(ListenSocket, NULL, NULL);
if (AcceptSocket == INVALID_SOCKET) {
wprintf(L"accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
delete[] pByteCamData;
return 1;
}
wprintf(L"Client connected.\n");
SendRecoredData(AcceptSocket); // <-- logic fix!
// No longer need client socket
closesocket(AcceptSocket); // <-- CLOSE_WAIT fix!
// No longer need server socket
closesocket(ListenSocket);
WSACleanup();
delete[] pByteCamData;
return 0;
}
VOID SendRecoredData(SOCKET socket2operation)
{
INT nCountDown = 5;
INT nSentData, nNumToSend;
BYTE *pData;
do
{
if (nCountDown == 0)
{
nCountDown = 5;
pData = pByteCamData;
nNumToSend = nSolution;
while (nNumToSend > 0) <-- send() fix!
{
nSentData = send(socket2operation, (char*)pData, nNumToSend, 0);
if (SOCKET_ERROR == nSentData) {
wprintf(L"send failed with error: %d\n", WSAGetLastError());
return;
}
pData += nSentData;
nNumToSend -= nSentData;
}
wprintf(L"Sent Camera Data OK [%d] Bytes\n", nSolution);
}
Sleep(PR_RECORED_TIME);
--nCountDown;
}
while (TRUE);
}
SendRecoredData(ListenSocket);
That should be
SendRecoredData(AcceptSocket);
which would have been causing an error in send() that you haven't told us about, and you are never closing AcceptSocket. That's what's causing the CLOSE_WAIT states. You don't need to look for them explicitly. Just fix your bugs.
I'm working on a c++ class that acts as a high-level wrapper around sockets in linux. While testing it, I purposely made the server's accept() call time out by having the client application sleep for a few seconds before calling connect().
However, after the server times out, the client application is still able to call connect() and send data without detecting an error. This is obviously a problem, because the server is not receiving the data, so the client should know the connection failed.
Here is my code. The server app calls Socket::accept_connection() and the client app sleeps and then calls Socket::connect_to().
// Accept a connection on the server side with a timeout
Socket *Socket::accept_connection(double timeout) {
Socket *new_connection = NULL;
socklen_t sin_size;
struct sockaddr_storage client_address; // Client's address
struct sockaddr_in client_port_address; // Client's port
char s[INET6_ADDRSTRLEN];
sin_size = sizeof client_address;
fd_set rfds;
struct timeval timeout_structure;
timeout_structure.tv_sec = (long)(timeout);
timeout_structure.tv_usec = int((timeout - timeout_structure.tv_sec) * 1e6);
struct timeval *timeout_ptr = NULL;
if(timeout > 0)
timeout_ptr = &timeout_structure;
// Loop until the timeout has been reached
while(true) {
FD_ZERO(&rfds);
FD_SET(socket_desc, &rfds);
if(select(socket_desc + 1, &rfds, NULL, NULL, timeout_ptr) > 0) {
int client_sock = accept(socket_desc, (struct sockaddr *)&client_address, &sin_size);
if(client_sock == -1) {
// Failed to connect
connected = false;
continue;
} else {
// Connected
inet_ntop(client_address.ss_family, get_in_addr((struct sockaddr *)&client_address), s, sizeof s);
getpeername(client_sock, (struct sockaddr*)&client_port_address, &sin_size);
int client_port = ntohs(client_port_address.sin_port);
// ...
}
} else {
// Timed out
connected = false;
std::cout << "accept() timed out\n";
break;
}
}
return new_connection;
}
// Connect to the given ip address and port
bool Socket::connect_to(std::string server_ip, int server_port, double timeout) {
connected = false;
// Create the socket and allocate memory for reading in data
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
struct timeval timeout_structure;
timeout_structure.tv_sec = (long)(timeout);
timeout_structure.tv_usec = int((timeout - timeout_structure.tv_sec) * 1e6);
struct timeval *timeout_ptr = NULL;
if(timeout > 0)
timeout_ptr = &timeout_structure;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(server_ip.c_str(), std::to_string(server_port).c_str(), &hints, &servinfo)) != 0) {
fprintf(stderr, "Socket error: connect_to, getaddrinfo: %s\n", gai_strerror(rv));
throw;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((socket_desc = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("Socket error: connect_to, socket");
continue;
}
int flags = 0, error = 0, ret = 0;
fd_set rset, wset;
socklen_t len = sizeof(error);
//clear out descriptor sets for select
//add socket to the descriptor sets
FD_ZERO(&rset);
FD_SET(socket_desc, &rset);
wset = rset; //structure assignment ok
//set socket nonblocking flag
if((flags = fcntl(socket_desc, F_GETFL, 0)) < 0)
continue;
if(fcntl(socket_desc, F_SETFL, flags | O_NONBLOCK) < 0)
continue;
//initiate non-blocking connect
if(ret = connect(socket_desc, p->ai_addr, p->ai_addrlen) == -1) {
if (errno != EINPROGRESS) {
close(socket_desc);
perror("Socket error: connect_to, could not connect");
continue;
}
}
if(ret != 0) { // If connect did not succeed right away
// We are waiting for connect to complete now
if((ret = select(socket_desc + 1, NULL, &wset, NULL, timeout_ptr)) < 0)
return false;
if(ret == 0){ //we had a timeout
errno = ETIMEDOUT;
return false;
}
//we had a positive return so a descriptor is ready
if(FD_ISSET(socket_desc, &rset) || FD_ISSET(socket_desc, &wset)){
if(getsockopt(socket_desc, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error != 0)
return false;
} else
return false;
if(error){ //check if we had a socket error
errno = error;
return false;
}
}
//put socket back in blocking mode
if(fcntl(socket_desc, F_SETFL, flags) < 0)
return false;
break;
}
if(p == NULL) {
fprintf(stderr, "Socket error: connect_to, failed to connect\n");
socket_desc = 0;
return false;
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
freeaddrinfo(servinfo); // all done with this structure
connected = true;
return connected;
}
This is normal, not a problem.
TCP maintains a listen backlog queue into which connections are placed that have been completed by the TCP stack but not yet accepted by the application.
TCP maintains a socket receive buffer per socket into which data is placed that has arrived from the peer and not yet been read by the application.
the client should know the connection failed.
It didn't fail. The server can accept it and read the data.
int tcp_sock = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in remoteaddr;
struct sockaddr_in localAddr;
short local_port = 22222;
short remote_port = 33333;
// local addr
localAddr.sin_family = AF_INET;
localAddr.sin_port = htons(local_port);
localAddr.sin_addr.s_addr = 0xC0A80AA5; // we don't give a shit
int addrLen = sizeof(struct sockaddr_in);
//Now bind TCP to local addr
int result = bind(tcp_sock,(struct sockaddr*)&localAddr,addrLen);
if (result < 0)
{
perror("\nbind failed");
close(tcp_sock);
return -1;
}
result = connect(tcp_sock, (struct sockaddr*)&remoteaddr, sizeof(struct sockaddr_in));
printf("\nConnect returned %d, error no: %d", result, errno);
Here the connect() call fails after a long time. Is there any way that I can make connect function return after a time of my choice? I tried calling close() from another thread but this doesn't change anything.
Put the socket into non-blocking mode before calling connect(), then you can use select() to specify a timeout. select() will tell you whether the connection succeeds or times out. If successful, you can put the socket back into blocking mode, if you want. If failed/timeout, close the socket instead.
int tcp_sock = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
...
int flags = fcntl(tcp_sock, F_GETFL, 0);
fcntl(tcp_sock, F_SETFL, flags | O_NONBLOCK);
int errCode = 0;
result = connect(tcp_sock, ...);
if (result < 0)
{
errCode = errno;
if (errCode == EINPROGRESS)
{
fd_set wfd;
FD_ZERO(&wfd);
FD_SET(tcp_sock, &wfd);
struct timeval timeout;
timeout.tv_sec = ...;
timeout.tv_usec = ...;
result = select(tcp_sock+1, NULL, &wfd, NULL, &timeout);
if (result > 0)
{
socklen_t len = sizeof(errCode);
result = getsockopt(tcp_sock, SOL_SOCKET, SO_ERROR, &errCode, &len);
if (result < 0)
errCode = errno;
else
result = (errCode == 0) ? 0 : -1;
}
else if (result == 0)
{
errCode = ETIMEDOUT;
result = -1;
}
else
{
errCode = errno;
}
}
}
if (result == 0)
{
// connected
fcntl(tcp_sock, F_SETFL, flags);
...
}
else
{
// error, use errCode as needed
...
}
Is there any way that I can make connect function return after a time of my choice?
Send the process a signal.
#define TIME_OUT_SECONDS (15)
void alarm_handler(int sig)
{
/* Do nothing. */
}
int main(void)
{
...
signal(alarm_handler);
alarm(TIME_OUT_SECONDS);
result = connect(tcp_sock, ...);
...
The only way to get out of connect if its taking time is to make the socket non-blocking. If its a blocking socket, you cannot get out.
Is there any way that I can make connect function return after a time of my choice?
Your choice is to mark the socket non-blocking. No other way round. Blocking means 'block' the executing thread until a event happens on the socket.You can't having blocking socket and timing out as per your needs go together.
Use, select or epoll mechanisms to monitor the sockets.
I use following code to check if a port is available or not:
bool ClassA::CheckPortTCP(short int dwPort , char *ipAddressStr)
{
struct sockaddr_in client;
int sock;
client.sin_family = AF_INET;
client.sin_port = htons(dwPort);
client.sin_addr.S_un.S_addr = inet_addr(ipAddressStr);
sock = (int) socket(AF_INET, SOCK_STREAM, 0);
int result = connect(sock, (struct sockaddr *) &client,sizeof(client));
// change to result == 0 -> failure in writing code too quick ;-)
if (result = 0) return true; // port is active and used
else return false;
}
The problem is if the port is opened but not connected the check failed! How can I easily examine that the port is available (not listening, not connected)?
e.g. port 21111 (output of netstat) -> my function doesn't recognize that the port is not free
TCP 0.0.0.0:21111 xxxxDUMMYxxxx:0 LISTENING
Thx
You have two errors: The first is that in the if statement you assign zero to result. The other is that connect returns -1 on failure to connect, and a non-negative value if it manages to connect.
There is also a problem that if you manage to connect, you don't close that connection.
the line client.sin_addr.S_un.S_addr = inet_addr(ipAddressStr); can not work for me. change it to:
bool CheckPortTCP(short int dwPort, char *ipAddressStr)
{
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup function failed with error: %d\n", iResult);
return false;
}
struct sockaddr_in client;
int sock;
client.sin_family = AF_INET;
client.sin_port = htons(dwPort);
client.sin_addr.s_addr = inet_addr(ipAddressStr);
sock = (int)socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
wprintf(L"ERROR: Socket function failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return false;
}
printf("INFO: Checking Port : %s:%d\n", ipAddressStr, dwPort);
int result = connect(sock, (struct sockaddr *) &client, sizeof(client));
if (result == SOCKET_ERROR) {
printf("ERROR: %s", WSAGetLastError());
WSACleanup();
return false;
}
else
{
WSACleanup();
closesocket(sock);
return true;
}
}