/* sender for internet stream demo */ #include #include #include #include #include #define ENDPACKET "end" #define MAXLINE 256 help_msg() { printf("format: ists -[d] hostname portno\n"); printf(" Option: d set debug mode\n"); } getline(s, lim) char s[]; int lim; { int c, i; for (i=0; i%s<\n", optarg); help_msg(); exit (1); } } rcv_name = argv[optind++]; if ((port_no = atoi(argv[optind])) < 1025) port_no = 1025; if (debug) printf("The receiver's host name is %s, port_no=%d\n", rcv_name, port_no); /* create socket on which to sent */ sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { perror("opening stream socket"); exit(1); } /* construct name of the socket to send to * gethostbyname() returns a structure including the network address * of the specified host from /etc/hosts. The port number is taken from * the cmd line * create name structure for the internet socket * use the name from cmd argument */ hp = gethostbyname(rcv_name); if (hp == 0) { fprintf(stderr, "%s: unknown host",rcv_name); exit(2); } bcopy(hp->h_addr, &server.sin_addr, hp->h_length); server.sin_family = AF_INET; server.sin_port = htons(port_no); if (connect(sock, &server, sizeof(server)) < 0) { perror("connecting stream socket"); exit(1); } printf("msg for receiver(\"$\" to exit):"); while ((n = getline(buf, MAXLINE)) > 0) { /* enter $ to break the connection */ if (buf[0] == '$') { printf("exiting...\n"); close(sock); exit(0); } /*send message */ if (write(sock, buf, n, 0, &server, sizeof(server)) < 0) perror("writing on stream socket"); bzero(fromBuf, sizeof(fromBuf)); if ((n=read(sock, fromBuf, 1024)) < 0) { perror("reading on stream socket"); break; } if (n == 0) { printf("receiver breaks the connection, exiting...\n"); break; } printf("reply msg=%s\n", fromBuf); printf("msg for receiver(\"$\" to exit):"); } close(sock); }