vfs: check userland buffers before reading them.
[haiku.git] / src / tests / kits / net / tcp_client.c
blobafae577ce18e2bc810f448e70189706d54b51850
1 /*
2 * a stream socket client demo
3 */
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>
16 #define PORT 1234 // the port client will be connecting to
17 #define MAXDATASIZE 100 // max number of bytes we can get at once
20 int
21 main(int argc, char **argv)
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
30 if (argc < 2) {
31 fprintf(stderr,"usage: tcp_client <hostname> [port]\n");
32 exit(1);
35 if (argc == 3)
36 port = atoi(argv[2]);
38 if ((he = gethostbyname(argv[1])) == NULL) {
39 // get the host info
40 perror("gethostbyname");
41 exit(1);
44 if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
45 perror("socket");
46 exit(1);
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);
54 if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {
55 perror("connect");
56 exit(1);
59 if (!fork()) {
60 int numBytes;
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;
71 buffer[numBytes] = '\0';
72 printf("%s", buffer);
74 } else {
75 while (1) {
76 // parent process
77 if (fgets(buffer, sizeof(buffer) - 1, stdin) == NULL) {
78 perror("fgets");
79 exit(1);
82 if ((send(sockfd, buffer, strlen(buffer), 0)) == -1) {
83 perror("send");
84 exit(1);
89 close(sockfd);
91 return 0;