본문 바로가기
Code review

[TCP/IP] hello world client 예제

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 hSocket;
        char message[30];
        int strLen;
        SOCKADDR_IN servAddr;

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

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

        // 서버 접속을 위한 소켓 생성
        hSocket = socket(PF_INET, SOCK_STREAM, 0);
        if(hSocket == INVALID_SOCKET)
        {
                ErrorHandling("hSocketet(), error");
        }

        memset(&servAddr, 0, sizeof(servAddr));
        servAddr.sin_family = AF_INET;
        servAddr.sin_addr.s_addr = inet_addr(argv[1]);
        servAddr.sin_port = htons(atoi(argv[2]));
       
        // 서버로 연결 요청
        if(connect(hSocket, (SOCKADDR*) &servAddr, sizeof(servAddr)) == SOCKET_ERROR)
        {
                ErrorHandling("Connect() error");
        }

        // 데이터 수신
        strLen = recv(hSocket, message, sizeof(message)-1, 0);
        if(strLen == -1)
        {
                ErrorHandling("read() error");
        }
        message[strLen] = 0;
        printf("Message from server : %s \n", message);

        // 연결 종료
        closesocket(hSocket);
        WSACleanup();
       
        return 0;
}
반응형

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

[C] fwrite 예제  (0) 2009.05.27
[TCP/IP] hello world server 예제  (0) 2009.05.27
[WinApi]self deleting executables  (0) 2009.05.27