Skip to content

Instantly share code, notes, and snippets.

@briankip
Last active October 7, 2015 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briankip/947b9678283cdbe0cea3 to your computer and use it in GitHub Desktop.
Save briankip/947b9678283cdbe0cea3 to your computer and use it in GitHub Desktop.
#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