Skip to content

Instantly share code, notes, and snippets.

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

Embed
What would you like to do?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#define QUEUE 1 //Queue for incoming connections
#define BUFFLENGTH 512 //Send buffer length
int main(int argc , char *argv[])
{
int sock_fd, len, newsock, readsize;
struct sockaddr_in server, client;
FILE *fp;
char *file = "oven.f";
char buffr[BUFFLENGTH];
if(argc < 2)
{
printf("Too few arguments. \nUsage : myftpd <port>\n");
exit(1);
}
int port = atoi(argv[1]);
sock_fd = socket(AF_INET , SOCK_STREAM , 0);
if (sock_fd == -1)
{
printf("Could not create socket!\n");
}
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(port);
//Bind
if( bind(sock_fd,(struct sockaddr *)&server , sizeof(server)) < 0)
{
printf("Server bind failed!\n");
return 1;
}
listen(sock_fd , QUEUE);
printf("Waiting for SYN\n");
while (newsock = accept(sock_fd, (struct sockaddr *)&client, (socklen_t*)&len)){
printf("New connect from %s.\n", inet_ntoa(client.sin_addr));
fp = fopen(file, "r");
if(fp == NULL)
{
printf("File 404'd \n");
return 1;
}
bzero(buffr, BUFFLENGTH);
while((readsize = fread(buffr, sizeof(char), BUFFLENGTH, fp)) > 0)
{
int sentbytes;
sentbytes = send(newsock, buffr, readsize, 0);
if(sentbytes < 0)
{
printf("Send to client failed.\n");
}
else if(sentbytes >= readsize) {
close(newsock);
}
bzero(buffr, BUFFLENGTH);
}
}
if (newsock < 0 ){
printf("Something went wrong\n");
}
printf("File sent. So long, and thanks for the fish... \n");
close(sock_fd);
}
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.