Thread: Winsock issues

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    66

    Winsock issues

    I am so utterly confused.

    I haven't used winsock in a while, and I wanted to make a project to get back into it so I made one, called it Krabz and opened up MSDN ( I don't know why I called it Krabz, but I did ).

    Now I've got code that to my knowledge should accept one connection, however it accepts no connection-at all. I've tried a lot of different modifications to it and I really have decided I just need some help. For some reason WSAStartup fails, according to my error checking, but when I look at the return value it's 0...which is supposed to mean it's not having an error? At least, that's my assumption! (MSDN said not to call wsagetlasterror so I didn't, and checked the actual return value, which it MSDN said nothing about a 0.)

    After that all of my error-checking pops up, so clearly something is wrong but I don't know what.

    KrabsChatServer.h
    Code:
    #ifndef KRABCHATSERVER_H_
    #define KRABCHATSERVER_H_
    
    #ifndef WIN32_LEAN_AND_MEAN			// Don't include Winsock 1.1 header
    #define WIN32_LEAN_AND_MEAN			// from windows.h
    #endif
    
    #include <windows.h>
    #include <tchar.h>
    #include <string>
    
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <iphlpapi.h>
    
    class KrabChatServer
    {
    private:
    	WSADATA	m_wsaData;
    	SOCKET	m_listenSocket;
    	SOCKET	m_clientSocket;			// eventually become an array
    
    	struct addrinfo *m_initServerResult,
    					*m_initServerPtr,
    					m_initServerHints;
    public:
    	KrabChatServer(void);
    	~KrabChatServer(void);
    
    	bool initWinsock();
    	bool initServer(std::string port);
    	bool beginListen();
    	bool beginAccept();
    	bool shutDownCon();
    	bool shutDownCon(SOCKET shutDownSocket);
    	bool shutDownWinsock();
    
    	/*int validate() { 
    		if ( m_clientSocket == INVALID_SOCKET ) 
    		{ 
    			return 1;
    		}
    		else
    		{ 
    			return 0;
    		} 
    		return 1;
    	}*/
    
    };
    
    #endif KRABCHATSERVER_H_
    KrabzChatServer.cpp
    Code:
    #include "KrabChatServer.h"
    
    KrabChatServer::KrabChatServer(void)
    {
    	// Initialize some sockets
    	m_listenSocket		= INVALID_SOCKET;
    	m_clientSocket		= INVALID_SOCKET;
    
    	// Initialize addrinfo
    	m_initServerResult	= NULL;
    	m_initServerPtr		= NULL;
    }
    
    KrabChatServer::~KrabChatServer(void)
    {
    }
    
    bool KrabChatServer::initWinsock()
    {
    	// Initialize winsock
    	if ( !WSAStartup(MAKEWORD(2, 2), &m_wsaData) )
    	{
    		// Failed to initialize winsock
    		MessageBox(NULL, _T("Failed to initialize winsock 2.2"), 
    			_T("Error!"), MB_OK);
    
    		return false;
    	}
    
    	// Success
    	return true;
    }
    
    bool KrabChatServer::initServer(std::string port)
    {
    	// Initialize the memory to zero
    	ZeroMemory( &m_initServerHints, sizeof(m_initServerHints));
    
    	// Set the properties of the connections the server will accept
    	m_initServerHints.ai_family	= AF_INET;
    	m_initServerHints.ai_socktype	= SOCK_STREAM;
    	m_initServerHints.ai_protocol	= IPPROTO_TCP;
    	m_initServerHints.ai_flags		= AI_PASSIVE;
    
    	// Resolve the local address and port to be used by the server
    	if (!getaddrinfo(NULL, port.c_str(), &m_initServerHints, &m_initServerResult))
    	{
    		// getaddrinfo failed
    		MessageBox(NULL, _T("getaddrinfo failed!"),
    			_T("Error!"), MB_OK);
    
    		WSACleanup();
    		return false;
    	}
    
    	// Success
    	return true;
    }
    
    bool KrabChatServer::beginListen()
    {
    	// Begin listening on m_listenSocket
    	m_listenSocket = socket(m_initServerResult->ai_family, 
    		m_initServerResult->ai_socktype,
    		m_initServerResult->ai_protocol);
    
    	// Success
    	return true;
    }
    
    bool KrabChatServer::beginAccept()
    {
    	// Begin to accept connections
    	// REVAMP: revamp this later to be it's own thread & while-looped
    	m_clientSocket = accept(m_listenSocket, NULL, NULL);
    
    	if (m_clientSocket == INVALID_SOCKET)
    	{
    		// failed to accept socket
    		MessageBox(NULL, _T("Accept socket failed!"), 
    			_T("Error!"), MB_OK);
    
    		closesocket(m_listenSocket);
    		WSACleanup();
    
    		return false;
    	}
    
    	// Success
    	return true;
    }
    
    bool KrabChatServer::shutDownCon()
    {
    	if ( shutdown(m_clientSocket, SD_SEND) == SOCKET_ERROR )
    	{
    		// Failed to shut down socket
    		MessageBox(NULL, _T("Failed to shut down socket, closing m_clientSocket..."),
    			_T("Error!"), MB_OK);
    
    		closesocket(m_clientSocket);
    		WSACleanup();
    
    		return false;
    	}
    
    	// Success
    	return true;
    }
    
    bool KrabChatServer::shutDownCon(SOCKET shutDownSocket)
    {
    	// Shuts down the connection
    	if ( shutDownSocket == INVALID_SOCKET )
    	{
    		// Invalid socket!
    		MessageBox(NULL, _T("Attempted to shut down an invalid socket..."),
    			_T("Error!"), MB_OK);
    
    		return false;
    	}
    
    	if ( shutdown(shutDownSocket, SD_SEND) == SOCKET_ERROR )
    	{
    		// Failed to shut down socket
    		MessageBox(NULL, _T("Failed to shut down socket, closing m_clientSocket..."),
    			_T("Error!"), MB_OK);
    
    		closesocket(m_clientSocket);
    		WSACleanup();
    
    		return false;
    	}
    
    	// Success
    	return true;
    }
    
    bool KrabChatServer::shutDownWinsock()
    {
    	// Cleans up winsock
    	closesocket(m_clientSocket);
    
    	WSACleanup();
    
    	// Success
    	return true;
    }
    main.cpp
    Code:
    // krabz.cpp
    
    #ifndef WIN32_LEAN_AND_MEAN			// Don't include Winsock 1.1 header
    #define WIN32_LEAN_AND_MEAN			// from windows.h
    #endif
    
    #include <windows.h>
    #include <tchar.h>
    
    #include "KrabChatServer.h"
    #include "KrabChatServerInterface.h"
    
    #include "KrabChatClient.h"
    #include "KrabChatClientInterface.h"
    
    
    // The windowclass and title
    static TCHAR szWindowClass[]	= _T("KMain");
    static TCHAR szTitle[]			= _T("Krabz Chat");
    
    // Create a server instance
    KrabChatServer kcs;
    
    // WndProc function to handle messages from the OS
    LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
    {
    	// Member variables we need to properly maintain our window
    	HDC			hdc;
    	PAINTSTRUCT	ps;
    
    	switch (message)
    	{
    	case WM_PAINT:
    		hdc = BeginPaint(hWnd, &ps);
    
    		// TODO: add draw code here
    
    		EndPaint(hWnd, &ps);
    		break;
    	case WM_DESTROY:
    		kcs.shutDownCon();
    		kcs.shutDownWinsock();
    
    		PostQuitMessage(0);
    		break;
    	case WM_LBUTTONDOWN:
    		// We should handle this
    		break;
    	case WM_RBUTTONDOWN:
    		// We should handle this
    		break;
    	default:
    		return DefWindowProc(hWnd, message, wParam, lParam);
    		break;
    	}
    }
    
    
    int WINAPI WinMain(HINSTANCE hInstance,
    				   HINSTANCE hPrevInstance,
    				   LPSTR lpCmdLine,
    				   int nShowCmd)
    {
    	// Initialize Winsock
    	kcs.initWinsock();
    
    	// Initalize the server
    	kcs.initServer("80");
    
    	// Begin to listen on the server
    	kcs.beginListen();
    
    	// Accept any possible connections
    	//while ( kcs.validate() == 1 )
    	kcs.beginAccept();
    
    	// Shut down in WndProc
    
    	// Create a WNDCLASSEX structure for our window
    	WNDCLASSEX wcex;
    
    	// Fill in the WNDCLASSEX structure
    	wcex.cbSize			= sizeof(WNDCLASSEX);
    	wcex.style			= 0;
    	wcex.lpfnWndProc	= WndProc;
    	wcex.cbClsExtra		= 0;
    	wcex.cbWndExtra		= 0;
    	wcex.hInstance		= hInstance;
    	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
    	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
    	wcex.lpszMenuName	= NULL;
    	wcex.lpszClassName	= szWindowClass;
    	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    
    	// Register the WNDCLASSEX structure
    	if (!RegisterClassEx(&wcex))
    	{
    		MessageBox(NULL, _T("Failed to register WNDCLASSEX structure!"), _T("Error!"),
    					MB_OK);
    
    		return 1;
    	}
    
    	// Create the actual window
    	HWND hWnd = CreateWindow(
    		szWindowClass,
    		szTitle,
    		WS_OVERLAPPEDWINDOW,
    		CW_USEDEFAULT, CW_USEDEFAULT,
    		420, 360,
    		NULL,
    		NULL,
    		hInstance,
    		NULL);
    
    	if (!hWnd)
    	{
    		MessageBox(NULL, _T("Failed to CreateWindow!"), _T("Error!"), MB_OK);
    
    		return 1;
    	}
    
    	// Display the window
    	ShowWindow(hWnd, nShowCmd);
    	UpdateWindow(hWnd);
    
    	// Create the message loop
    	MSG msg;
    	while (GetMessage(&msg, NULL, 0, 0))
    	{
    		TranslateMessage(&msg);
    		DispatchMessage(&msg);
    	}
    
    	return msg.wParam;
    }
    I hate to post so much code like that, but, I'm totally clueless as to what's wrong, I'm linking with the WS2_32.lib, I've put the WS2_32.dll file in every directory in my project and I'm using Visual C++ 2008 Express addition to do it. Any ideas at all? (Watch it be something simple and I'm just an idiot!)
    "When your work speaks for itself - don't interrupt!"

    -Samantha Ingraham.

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    This is wrong:
    Code:
    if ( !WSAStartup(MAKEWORD(2, 2), &m_wsaData) )
    WSAStartup returns 0 on success. False is defined as 0, so WSAStartup is succeeding, but you're treating it as if it failed.

  3. #3
    Registered User
    Join Date
    Oct 2007
    Posts
    66
    Quote Originally Posted by rags_to_riches View Post
    This is wrong:
    Code:
    if ( !WSAStartup(MAKEWORD(2, 2), &m_wsaData) )
    WSAStartup returns 0 on success. False is defined as 0, so WSAStartup is succeeding, but you're treating it as if it failed.
    Oh, how stupid of me. I should have remembered that :x Thanks though ^^
    "When your work speaks for itself - don't interrupt!"

    -Samantha Ingraham.

  4. #4
    Registered User
    Join Date
    Apr 2006
    Posts
    137
    If you have further problems, you can compare to these winsock tutorials and check your work.
    Winsock Client Tutorial
    Winsock Server Tutorial
    ★ Inferno provides Programming Tutorials in a variety of languages. Join our Programming Forums. ★

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. winsock select fdset issues
    By yahn in forum C++ Programming
    Replies: 3
    Last Post: 01-15-2006, 10:05 AM
  2. Winsock Messaging Program
    By Morgul in forum Windows Programming
    Replies: 13
    Last Post: 04-25-2005, 04:00 PM
  3. Winsock - Where do i start?
    By Brain Cell in forum Networking/Device Communication
    Replies: 5
    Last Post: 02-14-2005, 01:39 PM
  4. Where do I initialize Winsock and catch messages for it?
    By Lithorien in forum Windows Programming
    Replies: 10
    Last Post: 12-30-2004, 12:11 PM
  5. winsock
    By pode in forum Networking/Device Communication
    Replies: 2
    Last Post: 09-26-2003, 12:45 AM