파일전송하는데 그냥 write, read를 사용하는 경우에는

TEXT파일만 전송하는 문제가 생겼습니다. 

그래서 바이너리 파일 전송을 해야해서 여기저기 참고해서 작성했습니다. 


참고 : http://altibase.net/66


추가해야할 해더파일은

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

이렇습니다. 


아래의 소스코드가 맘대로 복사되게 해야하는데 방법을 모르겠습니다. 

아시는 분은 좀 알려주시길...


파일 사이즈를 얻는 방식은 2가지가 있습니다. 하나는 주석처리함.

----

int main(int argc, char **argv)
{
    int server_sockfd, client_sockfd;
    int state, client_len;
    size_t fsize = 0, nsize = 0, fpsize = 0;
    size_t fsize2 = 0;
    size_t fsize3 = 0;
    FILE *file = NULL;

    int ret;
    struct stat file_stat;

    struct sockaddr_in clientaddr, serveraddr;

    char buf[256];
    memset(buf, 0x00, 256);
    state = 0;

    client_len = sizeof(clientaddr);

    if ((server_sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket error : ");
        exit(0);
    }

    memset(&serveraddr,0x00, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serveraddr.sin_port = htons(8002);

    state = bind(server_sockfd , (struct sockaddr *)&serveraddr,
            sizeof(serveraddr));
    if (state == -1) {
        perror("bind error : ");
        exit(0);
    }
    state = listen(server_sockfd, 5);
    if (state == -1) {
        perror("listen error : ");
        exit(0);
    }


    file = fopen("test.jpg", "rb");
    fseek(file, 0, SEEK_END);
    fsize = ftell(file);
    fseek(file, 0, SEEK_SET);

    /*
    ret = lstat("test.jpg", &file_stat);
    if (ret < 0) {
        return -1;
    }
    if (file_stat.st_size == 0) {
        return -1;
    }

    fsize3 = file_stat.st_size;
    printf("file size 1 [%d]\n", fsize);
    printf("file size 2 [%d]\n", fsize3);
    */

    client_sockfd = accept(server_sockfd,
            (struct sockaddr *)&clientaddr, &client_len);
    printf("file size [%d]\n", fsize);
    fsize2 = htonl(fsize);
    printf("file size [%d]\n", fsize2);

    send(client_sockfd, &fsize2, sizeof(fsize), 0);

    while(nsize != fsize)
    {
        fpsize = fread(buf, 1, 256, file);
        nsize = nsize+fpsize;
        send(client_sockfd, buf, fpsize, 0);
    }
    printf("file send \n");
    close(client_sockfd);
    fclose(file);

    return 0;
}


----

반응형

'Language > C' 카테고리의 다른 글

switch case문과 if문의 성능차이  (8) 2012.10.31
바이너리 파일전송 C언어 예제 -클라이언트-  (8) 2012.10.18
itoa 함수 예제  (7) 2012.10.17
strspn 함수 예제  (7) 2012.09.20
strcmp 함수 예제  (6) 2012.08.17

+ Recent posts