|
CS473 - Computer Networks
| Displaying exercises/e4/solution/say.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <time.h>
#define BUFSIZE 4096
#define K 1024
/*
#define UNIX_PATH_MAX 108
struct sockaddr_un {
sa_family_t sun_family; // AF_UNIX
char sun_path[UNIX_PATH_MAX]; // pathname
};
*/
int main(int argc, char *argv[])
{
struct sockaddr_un name;
char *sock_path = "/tmp/listen";
char buf[K];
int r;
if (argc > 1) sock_path = argv[1];
if (access(sock_path, W_OK) != 0) {
printf("Unable to find socket file %s\n", sock_path);
exit(0);
}
/* Create socket, initially un-connected. */
int sock = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sock < 0) {
perror("socket");
exit(1);
}
/* Define name (filesystem socket file) to send to: */
name.sun_family = AF_UNIX;
strcpy(name.sun_path, sock_path);
printf("Type Ctrl-D to quit:\n");
while((r = read(STDIN_FILENO, buf, K)) > 0) {
if (sendto(sock, buf, r, 0, (struct sockaddr *)&name,
sizeof(struct sockaddr_un)) < 0) {
perror("sendto");
exit(1);
}
}
close(sock);
return 0;
}
|