Last active
October 7, 2015 04:51
-
-
Save briankip/50cb265b5e052252abe2 to your computer and use it in GitHub Desktop.
client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <arpa/inet.h> | |
#include <unistd.h> | |
#include <string.h> | |
#include <netdb.h> | |
#include <sys/types.h> | |
#include <netinet/in.h> | |
#include <sys/socket.h> | |
#define LENGTH 512 // Buffer length | |
int main(int argc, char *argv[]) | |
{ | |
int sockfd; | |
char recvbuf[LENGTH]; | |
struct sockaddr_in remote_addr; | |
char *server; | |
if(argc < 4){ | |
printf("Too few arguments. \nUsage : myftpdc <filename> <server> <port>\n"); | |
} | |
server = argv[2]; | |
int port = atoi(argv[3]); | |
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) | |
{ | |
printf("Socket creation failed!\n"); | |
return (0); | |
} | |
remote_addr.sin_family = AF_INET; | |
remote_addr.sin_port = htons(port); | |
inet_pton(AF_INET, server, &remote_addr.sin_addr); | |
if (connect(sockfd, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr)) == -1) | |
{ | |
printf ("Failed to connect to the host!\n"); | |
return (0); | |
} | |
else printf("Connected ...!\n"); | |
char* f_name = argv[1]; | |
FILE *fp = fopen(f_name, "a"); | |
if(fp == NULL) | |
{ | |
printf("File %s cannot be opened. Check permissions\n", f_name); | |
} | |
else | |
{ | |
bzero(recvbuf, LENGTH); | |
int f_block_sz; | |
while(f_block_sz = recv(sockfd, recvbuf, LENGTH, 0)) | |
{ | |
int write_sz = fwrite(recvbuf, sizeof(char), f_block_sz, fp); | |
if(write_sz < f_block_sz) | |
{ | |
printf("File write failed.\n"); | |
break; | |
} | |
if(f_block_sz < 0) | |
{ | |
printf("Receive file error.\n"); | |
break; | |
} | |
else if(f_block_sz = 0){ | |
printf("No more data. Closing connection.\n"); | |
break; | |
} | |
bzero(recvbuf, LENGTH); | |
} | |
} | |
close (sockfd); | |
printf("Connection ended.\n"); | |
return (0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment