Skip to content

Instantly share code, notes, and snippets.

@zellux
Created July 1, 2011 03:17
Show Gist options
  • Save zellux/1057806 to your computer and use it in GitHub Desktop.
Save zellux/1057806 to your computer and use it in GitHub Desktop.
UDP file transfer
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <fcntl.h>
#define SERV_PORT 49312
#define MAXLINE 1024
char *END_FLAG = "================END";
int main(int argc, char **argv)
{
int sockfd, n, fd;
struct sockaddr_in servaddr;
char buf[MAXLINE];
char *target, *path;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
path = argv[2];
target = argv[3];
sendto(sockfd, target, strlen(target), 0, (struct sockaddr *) &servaddr, sizeof(servaddr));
n = recvfrom(sockfd, buf, MAXLINE, 0, NULL, NULL);
if (!strncmp(buf, "ok", 2)) {
printf("Filename sent.\n");
}
fd = open(path, O_RDONLY);
while ((n = read(fd, buf, MAXLINE)) > 0) {
sendto(sockfd, buf, n, 0, (struct sockaddr *) &servaddr, sizeof(servaddr));
}
sendto(sockfd, END_FLAG, strlen(END_FLAG), 0, (struct sockaddr *) &servaddr, sizeof(servaddr));
return 0;
}
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define SERV_PORT 49312
#define MAXLINE 1024
char *END_FLAG = "================END";
void run(int sockfd, struct sockaddr *cliaddr, socklen_t clilen)
{
int n, fd;
socklen_t len;
char buf[MAXLINE];
len = clilen;
n = recvfrom(sockfd, buf, MAXLINE, 0, cliaddr, &len);
buf[n] = 0;
printf("Received from client: [%s]\n", buf);
sendto(sockfd, "ok", strlen("ok"), 0, cliaddr, len);
fd = open(buf, O_RDWR | O_CREAT, 0666);
while ((n = recvfrom(sockfd, buf, MAXLINE, 0, cliaddr, &len))) {
buf[n] = 0;
printf("%s", buf);
if (!(strcmp(buf, END_FLAG))) {
break;
}
write(fd, buf, n);
}
close(fd);
}
int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr, cliaddr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
run(sockfd, (struct sockaddr *) &cliaddr, sizeof(cliaddr));
return 0;
}
@ivansandev
Copy link

Would be awesome if it can be made to work with larger files (currently packets get lost on 15MB file...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment