user13357924
user13357924

Reputation: 1

Why am I not able to change my socket from blocking to nonblocking?

When my connect() function calls I get a 10035 connect error after putting my socket into nonbloking mode? My code should work without that error. Anyone tell me why this is happening?

#include <stdio.h>
#include <winsock2.h>
#include <windows.h>
#include <string.h>
#include <iostream>
#include <string>
#include <stdio.h>


#pragma comment(lib,"ws2_32.lib") //Winsock Library

#pragma comment(lib,"ws2_32")



using namespace std;

const int arrsize = 1;



int main(int argc , char **argv)
{

//Declare WSADATA structure containing information about windows sockets implementation.
WSADATA wsa;
//Create a socket object
SOCKET s;

struct sockaddr_in server;
const char *message;
char server_reply[arrsize];
int recv_size;


//Create socket.
cout << "Creating socket for connection." << endl;
if((s = socket(AF_INET , SOCK_STREAM , 0)) == INVALID_SOCKET)
{
    printf("Could not create socket : %d" , WSAGetLastError());
}

Right here. Why do I keep getting a error from my connect() function? The error is 10035. I am trying to make my socket nonblocking mode.

u_long mode = 1;  //For nonblocking mode.
ioctlsocket(s, FIONBIO, &mode);


char address[100] = "172.217.23.36";

server.sin_addr.s_addr = inet_addr(address);

server.sin_family = AF_INET;

server.sin_port = htons( 80 );


//Establish connection.
if ( connect(s, (struct sockaddr *)&server , sizeof(server)) < 0 )
{
    puts("Function connect() did not connect.");
    printf ( "  %d", WSAGetLastError() );
    return 1;
}



message = "GET / HTTP/1.1 \r\n\r\n";

if( send(s , message , strlen(message)+1, 0) < 0)
{
    puts("Function send() failed.");
    return 1;
}

if ( (recv_size = recv(s , server_reply , arrsize, 0)) == SOCKET_ERROR )
{
    puts("Function recv failed.");
    return 1;
}

closesocket(s);

//Terminate use of Winsock 2 DLL by calling WSACleanup() function.
WSACleanup();

return 0;

}

Upvotes: 0

Views: 462

Answers (1)

Zan Lynx
Zan Lynx

Reputation: 54325

So you have an error code. The very first thing to do is read the documentation:

10035: WSAEWOULDBLOCK. Resource temporarily unavailable. This error is returned from operations on nonblocking sockets that cannot be completed immediately,

So the error you have is a direct result of having a non-blocking socket.

You need to use some appropriate wait function and once it signals readiness, then you can finish the connect operation.

https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-connect

Upvotes: 2

Related Questions