bingoStack
bingoStack

Reputation: 47

winsock client socket is invalid

I want to connect to a specific server with this client-code using winsock. But the created socket is invalid, so that I get "INVALID SOCKET".

//Creating a socket for connecting to server
SOCKET hSocket;
hSocket = socket(AF_INET, SOCK_STREAM,0);
if (hSocket == INVALID_SOCKET)   //this is true!
{
    cout << "INVALID SOCKET" << endl;
}

/* This code assumes a socket has been created and its handle
is stored in a variable called hSocket */
sockaddr_in sockAddr;

sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(54123);
sockAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

// Connect to the server
if (connect(hSocket, (sockaddr*)(&sockAddr), sizeof(sockAddr)) != 0)
{
    cout << "ERROR while connecting" << endl;
}

Upvotes: 1

Views: 961

Answers (1)

DimChtz
DimChtz

Reputation: 4313

The only problem I can think of is that you didn't WSAStartup() the winsock. Please check https://msdn.microsoft.com/en-us/library/windows/desktop/ms742213%28v=vs.85%29.aspx if you didn't. You can also use WSAGetLastError to see what's wrong.

Add at the top of your code:

WSADATA wsaData;

//activate ws2_32.lib
int res = WSAStartup(MAKEWORD(2, 0), &wsaData);
if (res == 0){
    cout << "WSAStartup successful" << endl;
}
else {
    cout << "Error WSAStartup" << endl;
    return -201;
}

Upvotes: 3

Related Questions