2008-11-06

윈도우에서 간단한 socket programing 이 필요할 때

헤더파일

#include "windows.h"
#include "winsock2.h"


라이브러리
ws2_32.lib

초기화
프로그램이 시작할 때 한 번 해준다.

WSADATA wsaData;
WORD version;
int error;

version = MAKEWORD( 2, 0 );

error = WSAStartup( version, &wsaData );

/* check for error */
if ( error != 0 )
{
/* error occured */
return FALSE;
}

/* check for correct version */
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 0 )
{
/* incorrect WinSock version */
WSACleanup();
return FALSE;
}

/* WinSock has been initialized */


소켓 생성

SOCKET server;
server = socket(AF_INET, SOCK_STREAM, 0);


서버 시작하기


struct sockaddr_in sin;
memset(&sin, 0, sizeof (sin));
sin.sin_family = AF_INET;
sin.sin_Addrs_addr = INADDR_ANY;
sin.sin_port = htons(8080);

if (bind(server, &sin, sizeof(sin)) == SOCKET_ERROR) {
return FALSE;
}


클라이언트 리슨

while ( listen( server, SOMAXCONN ) == SOCKET_ERROR );


Server: Accepting Connection

SOCKET client;
int length;

length = sizeof sin;
client = accept( server, &sin, &length );


Client: Create Socket


SOCKET client;
client = socket( AF_INET, SOCK_STREAM, 0 );


Client: Get Host

struct hostent host;
host = gethostbyname( "async5-5.remote.ualberta.ca" );

Client: Connecting to Server

struct sockaddr_in sin;

memset( &sin, 0, sizeof sin );

sin.sin_family = AF_INET;
sin.sin_addr.s_addr = ((struct in_addr *)(host->h_addr))->s_addr;
sin.sin_point = htons( 21 );

if ( connect( client, &sin, sizeof sin ) == SOCKET_ERROR )
{
/* could not connect to server */
return FALSE;
}


Closing Socket

closesocket( server );


WinSock: Shutdown

WSACleanup();

댓글 없음: