• 분류 전체보기
    • 갈무리
    • 씨플플
    • SPRING
    • PI
    • ALGORITHM
    • DIARY
    • (∗❛ᴗ❛∗)
    • (●'◡'●)
    • 민디의 취준일기 (202301~)
  1. [2792] 보석상자 2020.04.01
  2. [10026] 적록색약 2020.03.09
  3. [1431] 시리얼번호 2020.02.19
  4. [C] 퀵소트 2020.02.19
[C] TCP 소켓프로그래밍 파일전송 (서버, 클라이언트) #ALGORITHM
2020. 2. 15.

클라이언트 → 서버로 파일을 전송하는 코드로

텍스트파일 뿐만아니라 .jpg .wav 파일같은 특수파일도 전송가능합니당!

 

주석처리된 파일사이즈 전송부분은 해제하고 사용하셔도 돼요!

 

$ gcc server.c -o server

$/* ./server <포트번호> */
$ ./server 5241
$ gcc client.c -o client

$ /*./client <IP 주소> <포트번호> */
$ ./client.c 127.0.0.1 5241

 

1. 클라이언트


/* client.c */

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

void error_handling(char *message);
int main(int argc, char* argv[]){

	int serv_sock, fd;
    	int str_len, len;
	struct sockaddr_in serv_addr;
	char message[30], buf[BUFSIZ];
    	FILE* file = NULL;
    
	if(argc!=3){
		printf("Usage : %s <IP> <PORT> \n", argv[0]);
		exit(1);
	}

	serv_sock = socket(PF_INET, SOCK_STREAM, 0);
    
	if(serv_sock == -1)
		error_handling("socket() error");
        
	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family=AF_INET;
	serv_addr.sin_addr.s_addr=inet_addr(argv[1]);
	serv_addr.sin_port=htons(atoi(argv[2]));
    
	if(connect(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))==-1) 
		error_handling("connect() error!");
	
    // test
	str_len=read(serv_sock, message, sizeof(message)-1);

	if(str_len==-1)
		error_handling("read() error!");
	printf("Message from server: %s \n", message);
    
	// jpg 
	size_t fsize, nsize = 0;
	size_t fsize2;
    
    /* 전송할 파일 이름을 작성합니다 */
	file = fopen("aurora.jpg" /* 파일이름 */, "rb");
	
    /* 파일 크기 계산 */
    // move file pointer to end
	fseek(file, 0, SEEK_END);
	// calculate file size
	fsize=ftell(file);
	// move file pointer to first
	fseek(file, 0, SEEK_SET);

	// send file size first
	// fsize2 = htonl(fsize);
	// send file size
	// send(serv_sock, &fsize2, sizeof(fsize), 0);

	// send file contents
	while (nsize!=fsize) {
		// read from file to buf
		// 1byte * 256 count = 256byte => buf[256];
		int fpsize = fread(buf, 1, 256, file);
		nsize += fpsize;
		send(serv_sock, buf, fpsize, 0);
	}	

	fclose(file);
	close(serv_sock);
	return 0;
}

void error_handling(char *message){
	fputs(message, stderr);
	fputc('\n', stderr);
	exit(1);
}

 

2. 서버


/* server.c */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

void error_handling(char *message);

int main(int argc, char *argv[])
{
	int serv_sock;
	int clnt_sock;
	char buf[256];
	struct sockaddr_in serv_addr;
	struct sockaddr_in clnt_addr;
	socklen_t clnt_addr_size;

	char message[]="Hello World!";
	
	if(argc!=2){
		printf("Usage : %s <port>\n", argv[0]);
		exit(1);
	}
	
	serv_sock=socket(PF_INET, SOCK_STREAM, 0);
	if(serv_sock == -1)
		error_handling("socket() error");
			
	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family=AF_INET;
	serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
	serv_addr.sin_port=htons(atoi(argv[1]));
	
	if(bind(serv_sock, (struct sockaddr*) &serv_addr, sizeof(serv_addr))==-1 )
		error_handling("bind() error"); 
	
	if(listen(serv_sock, 5)==-1)
		error_handling("listen() error");
	
	clnt_addr_size=sizeof(clnt_addr);  
	clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_addr,&clnt_addr_size);
	if(clnt_sock==-1)
		error_handling("accept() error");  
	
	write(clnt_sock, message, sizeof(message));
	int nbyte = 256;
    size_t filesize = 0, bufsize = 0;
    FILE *file = NULL;

    file = fopen("aurora.jpg"/* 새로 만들 파일 이름 */, "wb");

    //ntohl(filesize);
	//recv filesize

	//recv(clnt_sock, &filesize, sizeof(filesize), 0);
    //ntohl(filesize);
	//printf("file size = [%ld]\n", filesize);
    bufsize = 256;

    while(/*filesize != 0*/nbyte!=0) {
 		//if(filesize < 256) bufsize = filesize;
        nbyte = recv(clnt_sock, buf, bufsize, 0);
		//printf("filesize:%ld nbyte: %d\n", filesize, nbyte);

 		//filesize = filesize -nbyte;

        fwrite(buf, sizeof(char), nbyte, file);		
        //nbyte = 0;
    }
 
/*
	while((nbyte = recv(clnt_sock, buf, bufsize, 0) != 0)){
 		fwrite(buf, sizeof(char), nbyte, file);
	}
*/	

	fclose(file);
	close(clnt_sock);	
	close(serv_sock);
	return 0;
}

void error_handling(char *message)
{
	fputs(message, stderr);
	fputc('\n', stderr);
	exit(1);
}

 


서버와 클라이언트를 구분하기 위해 파일별로 폴더를 나누어 실행해보았습니다

client 폴더 안의 aurora.jpg 를 server 폴더로 전송해보겠습니다.

텍스트 파일은 이제 식상하잖아 ^!^

 

 

 

현재 server 폴더안에는 server.c 말고 다른 파일은 없습니다

 

 

 

 

server.c를 컴파일 한다음 서버를 먼저 실행시키고

$ gcc server.c -o server
$ ./server 5241

 

 

 

 

client.c 를 컴파일하고 실행시키면

$ gcc client.c -o client
$ ./client 127.0.0.1 5241

 

서버와 연결되고 Hello World를 받아 출력합니다. 그리고 사진을 전송

 

 

 

 

프로그램이 끝나면 server 폴더에 aurora.jpg 파일이 잘 전송된 걸 확인 할 수 있습니다.

 

 

 

티스토리툴바