Close failed to close () with WSAEOPNOTSUPP
I have an application using sockets (which I didn't write, so carry with me) and when I try to close the socket shutesocket () fails with WSAEOPNOTSUPP error and the socket sticks around ... as in, it's not completely deleted.
The socket is created like this:
bool Socket::CreateConnection()
{
int error;
struct addrinfo hints;
struct addrinfo *list = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
error = getaddrinfo(socketAddress.c_str(), socketPort.c_str(), &hints, &list);
if (error)
{
Log().RecordError("Unable to initialize connection to server", WSAGetLastError(), EventTypeError);
}
for (struct addrinfo *ptr = list; ptr != NULL; ptr = ptr->ai_next)
{
connection = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (connection == INVALID_SOCKET)
{
Log().RecordError("Unable to initialize socket connection", WSAGetLastError(), EventTypeError);
break;
}
error = connect(connection, ptr->ai_addr, (int)ptr->ai_addrlen);
if (error == SOCKET_ERROR)
{
closesocket(connection);
connection = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(list);
return connection != INVALID_SOCKET;
}
And the destructor for the class:
Socket::~Socket()
{
int error;
if (connection != INVALID_SOCKET)
{
continueReading = false;
error = shutdown(connection, SD_SEND);
if (error != SOCKET_ERROR)
{
/* Finish any necessary receives to politely close the socket */
int length;
do
{
char buffer[1024];
length = recv(connection, buffer, sizeof(buffer)/sizeof(*buffer), MSG_WAITALL);
} while (length > 0);
}
else
{
Log().RecordError("Error shutting down connection to server", WSAGetLastError(), EventTypeError);
}
closesocket(connection); //Fails HERE
int wsa_err = WSAGetLastError();
if(wsa_err)
Log().RecordError("closesocket() error", wsa_err, EventTypeError);
}
if (winsockInitialized)
{
WSACleanup();
}
}
Does anyone know why this is happening?
a source to share
I'm not a windows socket guru, but I still have an attempt. Are you sure the code returned WSAGetLastError()
is about the call closesocket()
?
Quoting msdn :
... This is necessary because some functions may reset the last extended error code to 0 if they succeed ...
I am guessing that you may have a previous socket causing the call (?). Msdn says that after every call associated with a socket, you should disable it by calling WSASetLastError()
with 0.
Specifically, to reset the extended error code, use a call to the WSASetLastError function with the iError parameter set to zero.
a source to share