카테고리

asm (27) bootloader_x86_grub (1) C (92) compile (11) config (76) CPP (13) CSS (1) debugging (7) gimp (1) Go (1) html (1) Java (1) JavaScript (1) kernel (19) LibreOffice (3) Linux system progamming (21) MFC (1) opencv (4) OpenGL (1) PHP (1) Python (4) qemu (29) shell (3) socket (7) troubleshooting (2) ubuntu18.04 (2) windows (1)

2018/12/11

socket 파일 전송 클라이언트

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

void error(const char *msg){
perror(msg);
exit(0);
}

int main(int argc, char *argv[]){
int sockfd, port_number, n;
struct sockaddr_in serv_addr;
struct hostent *server;

char buffer[1024];
if (argc < 3){
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
port_number = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(port_number);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");

bzero(buffer,1024);

FILE *f;

int words = 0;
char c;
f=fopen("HeaN.txt","r");
while((c=getc(f))!=EOF){ //Counting No of words in the file
fscanf(f , "%s" , buffer);
if(isspace(c)||c=='\t')
words++;
}
//printf("Words = %d \n"  , words); //Ignore


write(sockfd, &words, sizeof(int));
rewind(f);

/*      fseek(f, 0L, SEEK_END);    // tells size of the file. Not rquired for the functionality in code.
int sz = ftell(f); //Just written for curiosity.
printf("Size is %d \n" , sz);
rewind(f);
*/

char ch ;
while(ch != EOF){

fscanf(f , "%s" , buffer);
//printf("%s\n" , buffer); //Ignore
write(sockfd,buffer,1024);
ch = fgetc(f);
}
printf("The file was sent successfully");

close(sockfd);
return 0;
}

// compile: gcc -o client client.c
// ./client 127.0.0.1 9999

댓글 없음:

댓글 쓰기