Skip to content

Instantly share code, notes, and snippets.

@briankip briankip/myftpc.c
Last active Oct 7, 2015

Embed
What would you like to do?
client
#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
You can’t perform that action at this time.