1 .\" Copyright (c) 1986 Regents of the University of California. 2 .\" All rights reserved. The Berkeley software License Agreement 3 .\" specifies the terms and conditions for redistribution. 4 .\" 5 .\" @(#)streamwrite.c 6.2 (Berkeley) 05/08/86 6 .\" 7 #include <sys/types.h> 8 #include <sys/socket.h> 9 #include <netinet/in.h> 10 #include <netdb.h> 11 #include <stdio.h> 12 13 #define DATA "Half a league, half a league . . ." 14 15 /* 16 * This program creates a socket and initiates a connection with the socket 17 * given in the command line. One message is sent over the connection and 18 * then the socket is closed, ending the connection. The form of the command 19 * line is streamwrite hostname portnumber 20 */ 21 22 main(argc, argv) 23 int argc; 24 char *argv[]; 25 { 26 int sock; 27 struct sockaddr_in server; 28 struct hostent *hp, *gethostbyname(); 29 char buf[1024]; 30 31 /* Create socket */ 32 sock = socket(AF_INET, SOCK_STREAM, 0); 33 if (sock < 0) { 34 perror("opening stream socket"); 35 exit(1); 36 } 37 /* Connect socket using name specified by command line. */ 38 server.sin_family = AF_INET; 39 hp = gethostbyname(argv[1]); 40 if (hp == 0) { 41 fprintf(stderr, "%s: unknown host\n", argv[1]); 42 exit(2); 43 } 44 bcopy(hp->h_addr, &server.sin_addr, hp->h_length); 45 server.sin_port = htons(atoi(argv[2])); 46 47 if (connect(sock, &server, sizeof(server)) < 0) { 48 perror("connecting stream socket"); 49 exit(1); 50 } 51 if (write(sock, DATA, sizeof(DATA)) < 0) 52 perror("writing on stream socket"); 53 close(sock); 54 } 55