메뉴 건너뛰기

infra

[socket] linux용 c프로그램

박영식2010.04.19 03:18조회 수 3198댓글 0

  • 3
    • 글자 크기

# arm-linux-gcc -o 이름 소스코드
# gcc -o 이름 소스코드
로 컴파일 해서 embedded 장비나, linux용 프로그램에서 실행이 가능하다.


서버 프로그램 코드

    #include <stdio.h> 
    #include <stdlib.h> 
    #include <errno.h> 
    #include <string.h> 
    #include <sys/types.h> 
    #include <netinet/in.h> 
    #include <sys/socket.h> 
    #include <sys/wait.h> 

    #define MYPORT 3490    /* the port users will be connecting to */

    #define BACKLOG 10     /* how many pending connections queue will hold */

    main()
    {
        int sockfd, new_fd;  /* listen on sock_fd, new connection on new_fd */
        struct sockaddr_in my_addr;    /* my address information */
        struct sockaddr_in their_addr; /* connector's address information */
        int sin_size;

        if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
            perror("socket");
            exit(1);
        }

        my_addr.sin_family = AF_INET;         /* host byte order */
        my_addr.sin_port = htons(MYPORT);     /* short, network byte order */
        my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */
        bzero(&(my_addr.sin_zero), 8);        /* zero the rest of the struct */

        if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) 
                                                                      == -1) {
            perror("bind");
            exit(1);
        }

        if (listen(sockfd, BACKLOG) == -1) {
            perror("listen");
            exit(1);
        }

        while(1) {  /* main accept() loop */
            sin_size = sizeof(struct sockaddr_in);
            if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, 
                                                          &sin_size)) == -1) {
                perror("accept");
                continue;
            }
            printf("server: got connection from %sn", 
                                               inet_ntoa(their_addr.sin_addr));
            if (!fork()) { /* this is the child process */
                if (send(new_fd, "Hello, world!n", 14, 0) == -1)
                    perror("send");
                close(new_fd);
                exit(0);
            }
            close(new_fd);  /* parent doesn't need this */

            while(waitpid(-1,NULL,WNOHANG) > 0); /* clean up child processes */
        }
    }



이 프로그램을 컴파일 한 후 실행하면, client에서 telnet으로 테스트 할 수 있다.
# telnet ip주소 3490

3490은 port번호 이다. (소스 코드에 씌여 있다.)

아래는 서버측 화면이다.


클라이언트 프로그램은 아래와 같다. telnet을 통한 접속이 아니고, server프로그램이 실행되고 있으면,
# 프로그램이름 ip주소
로 하면, 결과를 볼 수 있다.(포트는 역시 3490이다)



    #include <stdio.h> 
    #include <stdlib.h> 
    #include <errno.h> 
    #include <string.h> 
    #include <netdb.h> 
    #include <sys/types.h> 
    #include <netinet/in.h> 
    #include <sys/socket.h> 

    #define PORT 3490    /* the port client will be connecting to */

    #define MAXDATASIZE 100 /* max number of bytes we can get at once */

    int main(int argc, char *argv[])
    {
        int sockfd, numbytes;  
        char buf[MAXDATASIZE];
        struct hostent *he;
        struct sockaddr_in their_addr; /* connector's address information */

        if (argc != 2) {
            fprintf(stderr,"usage: client hostnamen");
            exit(1);
        }

        if ((he=gethostbyname(argv[1])) == NULL) {  /* get the host info */
            herror("gethostbyname");
            exit(1);
        }

        if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
            perror("socket");
            exit(1);
        }

        their_addr.sin_family = AF_INET;      /* host byte order */
        their_addr.sin_port = htons(PORT);    /* short, network byte order */
        their_addr.sin_addr = *((struct in_addr *)he->h_addr);
        bzero(&(their_addr.sin_zero), 8);     /* zero the rest of the struct */

        if (connect(sockfd, (struct sockaddr *)&their_addr, 
                                              sizeof(struct sockaddr)) == -1) {
            perror("connect");
            exit(1);
        }

        if ((numbytes=recv(sockfd, buf, MAXDATASIZE, 0)) == -1) {
            perror("recv");
            exit(1);
        }

        buf[numbytes] = '';

        printf("Received: %s",buf);

        close(sockfd);

        return 0;
    }

박영식 (비회원)
  • 3
    • 글자 크기
[domxml] php에서 phpize, pecl을 이용해 사용가능하게 하기 (by 박영식) [tomcat] classpath와 외부 사이트 엑세스 허용 in 우분투 (by 박영식)

댓글 달기

박영식
2010.01.09 조회 3617
박영식
2009.08.01 조회 5627
박영식
2009.04.09 조회 3170
이전 1 ... 2 3 4 5 6 7 8 9 10 11다음
첨부 (3)
sp.PNG
21.5KB / Download 88
cp.PNG
10.5KB / Download 74
tn.PNG
27.7KB / Download 78
위로