BSD 4_3_Net_1 release
[unix-history] / doc / 07.ipctut / streamwrite.c
CommitLineData
23237d2e
KM
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.\"
95f51977 5.\" @(#)streamwrite.c 6.2 (Berkeley) 5/8/86
23237d2e
KM
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
23237d2e
KM
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
22main(argc, argv)
a43acb6b
MK
23 int argc;
24 char *argv[];
23237d2e 25{
a43acb6b 26 int sock;
23237d2e
KM
27 struct sockaddr_in server;
28 struct hostent *hp, *gethostbyname();
a43acb6b 29 char buf[1024];
23237d2e
KM
30
31 /* Create socket */
32 sock = socket(AF_INET, SOCK_STREAM, 0);
33 if (sock < 0) {
34 perror("opening stream socket");
a43acb6b 35 exit(1);
23237d2e
KM
36 }
37 /* Connect socket using name specified by command line. */
38 server.sin_family = AF_INET;
39 hp = gethostbyname(argv[1]);
a43acb6b
MK
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);
23237d2e
KM
45 server.sin_port = htons(atoi(argv[2]));
46
47 if (connect(sock, &server, sizeof(server)) < 0) {
23237d2e 48 perror("connecting stream socket");
a43acb6b 49 exit(1);
23237d2e
KM
50 }
51 if (write(sock, DATA, sizeof(DATA)) < 0)
52 perror("writing on stream socket");
53 close(sock);
54}