1/*
2 * a stream socket client demo
3 */
4
5#include <stdio.h>
6#include <stdlib.h>
7#include <unistd.h>
8#include <errno.h>
9#include <string.h>
10#include <netdb.h>
11#include <sys/types.h>
12#include <netinet/in.h>
13#include <sys/socket.h>
14
15
16#define PORT 1234		// the port client will be connecting to
17#define MAXDATASIZE 100	// max number of bytes we can get at once
18
19
20int
21main(int argc, char **argv)
22{
23	int sockfd;
24	char buffer[MAXDATASIZE];
25	short int port = PORT;
26	struct hostent *he;
27	struct sockaddr_in their_addr;
28		// connector's address information
29
30	if (argc < 2) {
31		fprintf(stderr,"usage: tcp_client <hostname> [port]\n");
32		exit(1);
33	}
34
35	if (argc == 3)
36		port = atoi(argv[2]);
37
38	if ((he = gethostbyname(argv[1])) == NULL) {
39		// get the host info
40		perror("gethostbyname");
41		exit(1);
42	}
43
44	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
45		perror("socket");
46		exit(1);
47	}
48
49	memset(&their_addr, 0, sizeof(their_addr));
50	their_addr.sin_family = AF_INET;
51	their_addr.sin_port = htons(port);
52	their_addr.sin_addr = *((struct in_addr *)he->h_addr);
53
54	if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {
55		perror("connect");
56		exit(1);
57	}
58
59	if (!fork()) {
60		int numBytes;
61
62		while (1) {
63			// child process
64			if ((numBytes = recv(sockfd, buffer, sizeof(buffer) - 1, 0)) == -1) {
65				perror("recv");
66				sleep(1);
67				// want the read thread to stay alive
68				continue;
69			}
70
71			buffer[numBytes] = '\0';
72			printf("%s", buffer);
73		}
74	} else {
75		while (1) {
76			// parent process
77			if (fgets(buffer, sizeof(buffer) - 1, stdin) == NULL) {
78				perror("fgets");
79				exit(1);
80			}
81
82			if ((send(sockfd, buffer, strlen(buffer), 0)) == -1) {
83				perror("send");
84				exit(1);
85			}
86		}
87	}
88
89	close(sockfd);
90
91	return 0;
92}
93
94