/*** * sserv1.c * * echo strings sent from a client process, reply appropriately, * until "quit" is encountered. * * To compile: gcc -lsocket -lnsl sserv1.c -o sserv1 * **/ #include #include #include #include #include #define SADDRESS "mysocket" #define BUFLEN 40 int main(int argc, char *argv[]) { struct sockaddr_un party_addr, own_addr; int sockfd; char buf[BUFLEN]; int party_len; int quitting; quitting = 1; /* */ memset(&own_addr, 0, sizeof(own_addr)); own_addr.sun_family = AF_UNIX; strcpy(own_addr.sun_path, SADDRESS); /* */ if ((sockfd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) { printf("can't create socket\n"); return 0; } /* */ unlink(own_addr.sun_path); if (bind(sockfd, (struct sockaddr *) &own_addr, sizeof(own_addr.sun_family)+ strlen(own_addr.sun_path)) < 0) { printf("can't bind socket!"); return 0; } /* */ while (1) { /* */ party_len = sizeof(party_addr); if (recvfrom(sockfd, buf, BUFLEN, 0,(struct sockaddr *) &party_addr, &party_len) < 0) { printf("server: error reading socket!"); return 0; } printf("server: received from client: %s \n", buf); /* ? */ quitting = (!strcmp(buf, "quit")); if (quitting) strcpy(buf, "quitting now!"); else if (!strcmp(buf, "ping!")) strcpy(buf, "pong!"); else strcpy(buf, "wrong string!"); /* */ if (sendto(sockfd, buf, strlen(buf) + 1, 0, (struct sockaddr *) &party_addr, party_len) != strlen(buf)+1) { printf("server: error writing socket!\n"); return 0; } if (quitting) break; } close(sockfd); return 0; }