Click here to Skip to main content
15,886,638 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I've came back to winsock after a while just to have fun and make a simple messenger program. The point is that I have the server up and running, actively listening for connections.
The client on the other hand, doesn't like something and I cannot understand what. It throws me a WSA 10014 Error, WSAEFAULT which indicates a bad address structure as I understand it.

Strangely enough, I cannot seem to find the problem. The structure looks about the same in the server (with a different s_addr, of course), and it seems to work fine there although I haven't managed to accept any connection in order to properly test it. Here's the code:

C++
#include <iostream>
#include <WinSock2.h>
using namespace std;

#pragma comment(lib, "ws2_32.lib")

class Client_Socket
{
private:
	WSADATA wsaData;
	WORD version;
	SOCKET server;
	struct sockaddr_in addr;
	int len;

public:
	// Constructor. 
	Client_Socket()
	{
		version = MAKEWORD(2, 0);

		// Initialize Winsock. 
		if(WSAStartup(version, &wsaData) != 0) {
			cout << "WSAStartup failed " << WSAGetLastError();
		}

		if(LOBYTE(wsaData.wVersion) != 2 && HIBYTE(wsaData.wVersion) != 0) {
			WSACleanup();
			cout << "WSock version incorrect " << WSAGetLastError();
		}

		// Create socket. 
		server = socket(AF_INET, SOCK_STREAM, 0);
		if(server == INVALID_SOCKET) {
			cout << "Socket creation failed " << WSAGetLastError();
		}

		// Prepare address structure. 
		memset(&addr, 0, sizeof(addr));
		addr.sin_family = AF_INET;
		addr.sin_addr.s_addr = inet_addr("127.0.0.1");
		addr.sin_port = htons(1324);
	}

	void connectToServer()
	{
		if(connect(server, (struct sockaddr*)&server, sizeof(server)) < 0) {
			cout << "Connection to server failed " << WSAGetLastError();
		} else {
			cout << "Connection established. ";
		}
	}

	~Client_Socket()
	{
		WSACleanup();
	}
};


Mind you it's object-oriented. In the main function I'm simply spawning a thread which instantiates and calls the connectToServer() method. So what's wrong with my address structure? Or maybe the I got the connect function wrong?

Thanks in advance.
Posted

1 solution

connect(server, (struct sockaddr*)&server, sizeof(server))

Looks like you're passing the "server" variable instead of the address structure.
 
Share this answer
 
Comments
Sergiu Petrica 8-May-15 11:48am    
Oh gods, that was such a newbie mistake jesus.. Would have probably scratched my head for a few more hours. It works fine now. Thank you so much.
Albert Holguin 8-May-15 12:38pm    
Happens... happy coding! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900