-
December 23rd, 2014, 06:27 PM
#1
Nonblocking connect and select() for writing
I'm trying to test a class that checks sockets for writability. Most of the time sockets should always be writable unless their buffers are full, but it's my understanding that polling for writability is the expected way to check if a nonblocking connect() call has completed.
However, what I'm seeing is that the socket is writable before I expect it to be, so I'm not sure what's going on.
This code is expected to work on both Windows and Linux.
Here is my setup:
Code:
// PollerSocket is a typedef of either int or SOCKET
PollerSocket server = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(0);
// Bind to any available port, then look it up so we know what to talk to.
::bind(server, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
listen(server, 1);
socklen_t len = sizeof(addr);
getsockname(server, reinterpret_cast<sockaddr*>(&addr), &len);
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
// addr is now our destination address.
PollerSocket client = socket(AF_INET, SOCK_STREAM, 0);
// Enable nonblocking connect.
#if defined(WINDOWS)
unsigned long nonblock = 1;
ioctlsocket(client, FIONBIO, &nonblock);
#else
int flags = fcntl(client, F_GETFL, 0);
fcntl(client, F_SETFL, flags | O_NONBLOCK);
#endif
int code = connect(client, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
#if defined(WINDOWS)
EXPECT_EQ(code, SOCKET_ERROR);
EXPECT_EQ(WSAEWOULDBLOCK, WSAGetLastError());
#else
EXPECT_EQ(-1, code);
EXPECT_EQ(EINPROGRESS, errno);
#endif
char buffer[] = "Hello";
ssize_t res = send(client, buffer, sizeof(buffer), 0);
EXPECT_EQ(-1, res);
The send() is succeeding when I think it should be failing with EWOULDBLOCK or ENOTCONN. Furthermore, a select() for writability on "client" is not blocking as I would expect it to on either platform.
Any ideas what's going on?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|