Looking at this in the fresh morning air, I realized what a mess I had made (no thanks to master5001, but much to RobSeace...)
So for posterity, here's my working code for binary transfer on a local unix socket (for which there may be a few uses, who knows?):
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>
int loclconn (char *socket, int fd) {
size_t size;
struct sockaddr_un peer;
peer.sun_family=AF_LOCAL;
strcpy(peer.sun_path,socket);
size=SUN_LEN(&peer);
return connect(fd,(struct sockaddr*)&peer,size);
}
int loclsckt (char *file) {
struct sockaddr_un name;
int sock;
size_t size;
if ((strlen(file)) > 107) return -2;
if ((sock=socket(PF_LOCAL,SOCK_STREAM,0)) < 0) return -1;
name.sun_family = AF_LOCAL;
strcpy(name.sun_path, file);
size=SUN_LEN(&name);
if ((bind(sock,(struct sockaddr*)&name,size) < 0)) return -3;
return sock;
}
int main (int argc, char *argv[]) {
int pid, CHLD, PRNT, IN;
size_t len;
int bytes;
char *buffer, *buffer2;
struct stat finfo;
FILE *fstRO = fopen(argv[1], "rb");
FILE *fstW = fopen("/root/test/image.jpg", "wb");
struct sockaddr addr;
if (fstRO == NULL) {
puts("valid filename required");
return -1;}
stat(argv[1],&finfo);
bytes=finfo.st_size;
buffer=malloc(bytes);
buffer2=malloc(bytes);
fread(buffer,bytes,1,fstRO);
fclose(fstRO);
PRNT=loclsckt("/root/test/testsock");
listen(PRNT,5);
if ((CHLD=socket(PF_LOCAL,SOCK_STREAM,0)) < 0) perror("socket");
pid=fork();
if (pid == 0) {
if (loclconn("/root/test/testsock",CHLD) < 0) perror("localconn");
if(write(CHLD,buffer,bytes) == -1) perror("write");
close(CHLD);
return;
}
IN=accept(PRNT,&addr,&len);
read(IN,buffer2,bytes);
close(IN);
close(PRNT);
unlink("/root/test/testsock");
fwrite(buffer2,bytes,1,fstW);
fclose(fstW);
}