If I have a MFC program that opens a socket connection, how would I test to see if the socket has succesfully opened or not?

Dani AI

Generated

A few clarifications and a practical option for the connect-timeout problem mentioned by , expanding on 's point about checking failures.

Winsock calls return socket-specific error codes, so use WSAGetLastError() (not GetLastError()) to read the failure reason. Also note that a blocking connect (for example CSocket::Connect or a plain blocking connect()) will block the calling thread until the OS TCP stack times out — that can be many seconds or longer, which explains why the call “just sits there.” For GUI apps, avoid blocking the main thread.

Three practical approaches

  • Use MFC’s CAsyncSocket and override OnConnect; start a UI or worker timer and treat lack of OnConnect by the deadline as a timeout.
  • Perform the blocking connect in a worker thread so the UI stays responsive.
  • Use a non-blocking socket and implement a timed wait (select) to detect success/failure within a chosen timeout.

Example (non-blocking connect + select + getsockopt)

// create socket, call WSAStartup first
u_long mode = 1; // non-blocking
ioctlsocket(s, FIONBIO, &mode);

int r = connect(s, (sockaddr*)&sa, sizeof(sa));
if (r == 0) { /* connected immediately */ }
else {
    int wserr = WSAGetLastError();
    if (wserr == WSAEWOULDBLOCK) {
        fd_set wf; FD_ZERO(&wf); FD_SET(s, &wf);
        timeval tv = { timeoutSecs, 0 };
        int sel = select(0, NULL, &wf, NULL, &tv);
        if (sel > 0 && FD_ISSET(s, &wf)) {
            int so_err = 0; int len = sizeof(so_err);
            getsockopt(s, SOL_SOCKET, SO_ERROR, (char*)&so_err, &len);
            if (so_err == 0) { /* connected */ }
            else { /* connect failed, so_err holds code */ }
        } else if (sel == 0) { /* timeout: close socket */ }
    } else { /* immediate connect failure: wserr */ }
}
// restore blocking mode if needed
mode = 0; ioctlsocket(s, FIONBIO, &mode);

Notes and troubleshooting

  • After a failed or timed-out connect, call closesocket() and report the WSA error (FormatMessage can produce readable text from the code).
  • Verify firewall/router and correct target IP/port.
  • For MFC GUI code prefer CAsyncSocket with OnConnect or move blocking calls to a worker thread to avoid freezing the UI.

Recommended Answers

All 4 Replies

If I have a MFC program that opens a socket connection, how would I test to see if the socket has succesfully opened or not?

almost any function in the winsock api returns the value SOCKET_ERROR in the event of failure. you only have to check this for errors. if you want details on the error number, you can use the GetLastError() function that will give the number of the error occured. Look up in the msdn link for error codes for a text explanation. you can also use the FormatMessage() function to programatically get the text explanation.


for eg.

if ( socket.function(  parameter1,... ) == SOCKET_ERROR )
       {
                  cout << GetLastError();
                  // do error processing
       }
       else
       {
                  //successfull operation
       }

What if I"m looking for an error on connect, for example a connection timeout? I tried adding your example to the socket.connect(ip,port) function, but it just sits there thinking.

here is the documentation for the connect function. you can find the error constants and the way to detect failure using it.

Sweet, Thanx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.