1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
// send them bytes!
ssize_t sendBytes(int sockfd, const void *buf, size_t len) {
const char *p = buf;
size_t sent = 0;
ssize_t result;
do {
result = send(sockfd,&p[sent],len,0);
if ( result > 0 ) {
// deal with whatever partial success we have
sent += result;
len -= result;
} else {
// something wrong
break;
}
} while ( len > 0 );
return result;
}
// sends an integer in network byte order
ssize_t sendInt(int sockfd, int value) {
long n = htonl(value);
return sendBytes(sockfd,&n,sizeof(n));
}
// sends a string, prefixed with it's length
ssize_t sendString(int sockfd, const char *str) {
size_t len = strlen(str);
ssize_t result = (sockfd,len);
if ( result <= 0 ) return result;
result = sendBytes(sockfd,str,len);
return result;
}
// send exactly one image, along with the necessary image length
ssize_t sendImage(int sockfd, const char *filename, size_t filelen) {
ssize_t result;
FILE *fin = fopen(filename, "rb");
if ( fin ) {
// Send the file length
result = sendInt(sockfd,filelen);
if ( result <= 0 ) { fclose(fin) ; return result; }
char buff[BUFSIZ];
size_t cnt;
while ((cnt = fread(buff, 1, sizeof buff, fin)) != 0) {
result = sendBytes(sockfd,buff,cnt);
if ( result <= 0 ) break;
}
fclose(fin);
}
return result;
}
// Send all the images in a directory
ssize_t sendDir(int sockfd, const char *dirname) {
DIR *dirp = opendir(".");
ssize_t result = 0;
for (struct dirent *dent; (dent = readdir(dirp)) != NULL; ) {
const char *filename = dent->d_name;
// check for self and parent directories
if (strcmp(filename, ".") == 0 || strcmp(filename, "..") == 0)
continue;
// other checks, like it's not a sub-directory or not an image?
struct stat file_stats;
if (stat(filename, &file_stats) == -1) {
perror(filename);
break;
}
result = sendImage(sockfd,filename,file_stats.st_size);
if ( result <= 0 ) break;
}
closedir(dirp);
return result;
}
int main ()
{
int sockfd = 0;
// add your open connection code here.
sendDir(sockfd,"/home/Desktop/pics");
}
| |