Click here to Skip to main content
15,884,388 members
Articles / Desktop Programming / MFC

Server Client Sockets

Rate me:
Please Sign up or sign in to vote.
4.76/5 (84 votes)
25 Apr 20039 min read 489.5K   15.2K   192  
Sample application Uses Server and client socket to establish exchange of data
#include <windows.h>
#include <winsock.h>

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

#define CS_ERROR 1
#define CS_OK 0

void sError(char*);

int WINAPI WinMain(HINSTANCE hHinst, HINSTANCE hPrevHinst, LPSTR lpCmdLine, int nShow)
{

	WORD version;
	WSADATA wsaData;
	int rVal=0;

	version = MAKEWORD(1,1);

	WSAStartup(version,(LPWSADATA)&wsaData);

	LPHOSTENT hostEntry;

	//store information about the server
	hostEntry = gethostbyname("hibbert");

	if(!hostEntry)
	{
		sError("Failed gethostbyname()");
		//WSACleanup();
		return CS_ERROR;
	}

	//create the socket
	SOCKET theSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

	if(theSocket == SOCKET_ERROR)
	{
		sError("Failed socket()");
		return CS_ERROR;
	}

	//Fill in the sockaddr_in struct
	SOCKADDR_IN serverInfo;

	serverInfo.sin_family = PF_INET;
	serverInfo.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);

	serverInfo.sin_port = htons(8888);

	rVal=connect(theSocket,(LPSOCKADDR)&serverInfo, sizeof(serverInfo));
	if(rVal==SOCKET_ERROR)
	{
		sError("Failed connect()");
		return CS_ERROR;
	}

	closesocket(theSocket);
	WSACleanup();
	MessageBox(NULL, "Connection was made", "SOCKET", MB_OK);
	return CS_OK;
}

void sError(char *str)
{
	MessageBox(NULL, str, "SOCKET ERROR", MB_OK);
	WSACleanup();
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions