'Programming/Linux Network'에 해당되는 글 1건

  1. 2010.07.12 Linux에서의 초간단 Echo Server
2010. 7. 12. 20:13

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
    int fd, new_fd, ret;
    char buff[1024];
    struct sockaddr_in my_addr = {0,};

    fd = socket( AF_INET, SOCK_STREAM, 0 );                               // 소켓생성.

    my_addr.sin_family     = AF_INET;
    my_addr.sin_port       = htons(7777);                                         // 포트번호 셋팅.
    my_addr.sin_addr.s_addr = inet_addr("192.168.200.129");             // 주소셋팅.

    if( bind( fd, (struct sockaddr*)&my_addr, sizeof my_addr) < 0 )   // 주소 바인딩.
    {
        perror("bind");
        exit(-1);
    }

    listen( fd, 10 );

    while(1)
    {
        new_fd = accept( fd, 0, 0 );                                                     // 클라이언트와 연결 및 새로운 소켓 생성.
        printf("새로운 클라이언트 접속 : new_fd=%d\n", new_fd);

        while( ret = read( new_fd, buff, sizeof buff ) )                           // 클라이언트로 부터 전송된 데이타 읽기.
             write( new_fd, buff, ret );                                                  // 읽은 데이타 전송

        printf("클라이언트 탈퇴 : new_fd=%d\n", new_fd);
        close( fd );
    }
    close( new_fd );

    return 0;
}


 

Posted by 어북어위크