Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Server Client Sockets

, 25 Apr 2003
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Emiliano
Web Developer
United Kingdom United Kingdom
No Biography provided

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150129.1 | Last Updated 26 Apr 2003
Article Copyright 2003 by Emiliano
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid