Code:
//simple winsock connection
#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <winsock.h>
#define PORT 25
#define MAXDATASIZE 100
struct hostent *he;
struct sockaddr_in server;
int numbytes;
char buf[MAXDATASIZE];
WSADATA wsdata;
SOCKET sock;
DWORD wsock;
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
WNDCLASSEX win = {0};
win.cbSize = sizeof(WNDCLASSEX);
static TCHAR szAppName[] = ("Basic Raw connection");
win.style = CS_HREDRAW | CS_VREDRAW;
win.lpfnWndProc = WindowProc;
win.cbClsExtra = 0;
win.cbWndExtra = 0;
win.hInstance = hInstance;
win.hIcon = LoadIcon(NULL, IDI_WINLOGO);
win.hCursor = LoadCursor(NULL, IDC_CROSS);
win.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
win.lpszMenuName = NULL;
win.lpszClassName = szAppName;
RegisterClassEx(&win);
HWND hWnd = CreateWindowEx(
WS_EX_CLIENTEDGE,
szAppName,
_T("Winsock Demo"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL
);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
MSG msg;
while(GetMessage(&msg, NULL, 0, 0) == TRUE)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_LBUTTONDOWN:
{
WSAStartup(0x0101,&wsdata);
sock = socket(AF_INET, SOCK_STREAM, 0);
he = gethostbyname("localhost");
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr = *((struct in_addr *)he->h_addr);
if(connect(sock,(struct sockaddr *)&server,sizeof(server)) == SOCKET_ERROR)
{
MessageBox(hWnd, "Error Connecting","",MB_OK);
return 0;
}
numbytes = recv(sock, buf, MAXDATASIZE, 0);
buf[numbytes] = '\0';
MessageBox(hWnd, buf, "Server response:", MB_OK);
closesocket(sock);
WSACleanup();
return 1;
}
break;
case WM_CREATE:
{
MessageBeep(0);
}
break;
case WM_PAINT:
{
PAINTSTRUCT paintst;
HDC hdc = BeginPaint(hWnd, &paintst);
EndPaint(hWnd, &paintst);
return 0;
}
break;
case WM_CLOSE:
{
SendMessage(hWnd, WM_DESTROY, wParam, lParam);
}
break;
case WM_DESTROY :
{
PostQuitMessage(0);
WSACleanup();
return 0;
}
default:
{
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
return 0;
}