/* sender for unix domain datagram demo */ #include #include #include #include help_msg() { printf("format: idgs -[d] unix_sock_path_name\n"); printf(" option: d set debug mode\n"); } main(argc, argv) int argc; char *argv[]; { int sock; struct sockaddr_un to; struct sockaddr_un addr; int n; char toBuf[1024]; char fromBuf[1024]; extern char *optarg; extern int optind; int option_exist = 0; int c; int debug = 0; int length; int flag; /* process command line args */ while ((c=getopt(argc,argv,"dn:")) != EOF) { option_exist = 1; switch(c) { case 'd': debug = 1; if (debug) printf("turn on debug mode.\n"); break; case '?': help_msg(); exit (1); default: fprintf (stderr, "unrecognized arg >%s<\n", optarg); help_msg(); exit (1); } } to.sun_family = AF_UNIX; strcpy(to.sun_path, argv[optind++]); printf("The receiver's sun_path is %s\n", to.sun_path); /* create socket from which to read */ sock = socket(AF_UNIX, SOCK_DGRAM, 0); if (sock < 0) { perror("opening datagram socket"); exit(1); } /* create name structure with wildcard using INADDR_ANY */ addr.sun_family = AF_UNIX; sprintf(addr.sun_path, "/tmp/cs522.%s.client", getlogin()); unlink(addr.sun_path); if (bind(sock, &addr, sizeof(struct sockaddr_un))) { perror("binding name to datagram socket"); exit(1); } printf("unix domain datagram client sun_path=%s\n", addr.sun_path); /*send message */ printf("sending message: This is packet one!\n"); sprintf(toBuf, "This is packet one!\n"); if (sendto(sock, toBuf, strlen(toBuf), 0, &to, sizeof(to)) < 0) perror("sending datagram message"); n = recv(sock, fromBuf, 1024, 0); if (n < 0) perror("receiving datagram message"); fromBuf[n] = 0; /* null terminate */ printf("number of bytes received=%d\n", n); printf("received ack msg=%s\n", fromBuf); unlink(addr.sun_path); close(sock); }