The following C code compiles to a file nc-send-file, and it will send a file to a raw tcp socket (such as netcat with the command: nc -l -p 8000 > myfile ), with progress indicator for every 64K bytes sent.
On Windows, compile it using MinGW the following Makefile:
nc-send-file:nc-send-file.c
gcc -Wall -O2 -o $@ $^ -s -lws2_32
clean:
rm -f nc-send-file.exe
C code:
#ifdef WIN32
#include "winsock2.h"
#else
#include "sys/socket.h"
#include "netinet/in.h"
#include "unistd.h"
#endif
#include "stdio.h"
int main(int argc, char**argv)
{
FILE * fd;
int sockfd,ret,n;
struct sockaddr_in servaddr;
char sendline[1024*64];
unsigned int totalbytes=0;
if (argc != 4)
{
printf("usage: client [IP address] [PORT] [File]\n");
exit(1);
}
#ifdef WIN32
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0){
fprintf(stderr, "WSAStartup() failed");
exit(1);
}
#endif
sockfd=socket(AF_INET,SOCK_STREAM,0);
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=inet_addr(argv[1]);
servaddr.sin_port=htons(atoi(argv[2]));
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))<0){
fprintf(stderr,"Error connecting to target.\n");
return -1;
}
fd=fopen(argv[3],"rb");
if (fd==NULL){
fprintf(stderr,"Opening file %s error\n",argv[3]);
return -1;
}
while (1){
ret=fread(sendline, 1, sizeof(sendline),fd);
if (ret==0){
if (feof(fd)){
printf("Finished. Total bytes sent:%u\n",totalbytes);
}else{
printf("Error.\n");
}
break;
}
n=send(sockfd,sendline,ret,0);
if (n!=ret){
printf("did not send all in the buffer. expecting %d sent %d exit.\n", ret, n);
return -1;
}
totalbytes+=ret;
printf("sending %d bytes, total %d bytes\n",ret, totalbytes);
}
fclose(fd);
#ifdef WIN32
closesocket(sockfd);
WSACleanup(); /* Cleanup Winsock */
#else
close(sockfd);
#endif
return 0;
}
No comments:
Post a Comment