본문 바로가기
Code review

[TCP/IP] hello world server 예제

by cafrisun 2009. 5. 27.
 
ws2_32.lib 를 사용. - TCP/IP 소켓프로그래밍 (윤성우 저) 참조

/*
==================================================
        Windows 기반의 "Hello World" 서버
==================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>


/*==================================================
        Error Message print
==================================================*/
void ErrorHandling(char *message)
{
        fputs(message, stderr);
        fputc('\n', stderr);
        exit(1);
}


/*==================================================
        Entry Point
==================================================*/
int main(int argc, char **argv)
{
        WSADATA wsaData;
        SOCKET hServSock;
        SOCKET hClntSock;
        SOCKADDR_IN servAddr;
        SOCKADDR_IN clntAddr;
        int szClntAddr;

        char message[] = "Hello World!\n";

        if(argc != 2)
        {
                printf("Usage : %s <port> \n", argv[0]);
                exit(1);
        }

        // Load Winsock 2.2 DLL
        if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
        {
                ErrorHandling("WSAStartup() error!");
        }

        // 서버 소켓 생성
        hServSock = socket(PF_INET, SOCK_STREAM, 0);
        if(hServSock == INVALID_SOCKET)
        {
                ErrorHandling("socket() error");
        }

        memset(&servAddr, 0, sizeof(servAddr));
        servAddr.sin_family = AF_INET;
        servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
        servAddr.sin_port = htons(atoi(argv[1]));

        // 소켓에 주소 할당
        if(bind(hServSock, (SOCKADDR*) &servAddr, sizeof(servAddr)) == SOCKET_ERROR)
        {
                ErrorHandling("bind() error");
        }

        // 연결 요청 대기 상태
        if(listen(hServSock, 5) == SOCKET_ERROR)
        {
                ErrorHandling("listen() error");
        }

        // 연결 요청 수락
        szClntAddr = sizeof(clntAddr);
        hClntSock = accept(hServSock, (SOCKADDR*) &clntAddr, &szClntAddr);
        if(hClntSock == INVALID_SOCKET)
        {
                ErrorHandling("accept() error");
        }

        // 데이터 전송
        send(hClntSock, message, sizeof(message), 0);

        // 연결 종료
        closesocket(hClntSock);
        WSACleanup();

        return 0;
}
반응형

'Code review' 카테고리의 다른 글

[TCP/IP] hello world client 예제  (0) 2009.05.27
[WinApi]self deleting executables  (0) 2009.05.27
[WinApi]Dialog base start 2  (0) 2009.05.27