2 * a stream socket client demo
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
21 main(int argc
, char **argv
)
24 char buffer
[MAXDATASIZE
];
25 short int port
= PORT
;
27 struct sockaddr_in their_addr
;
28 // connector's address information
31 fprintf(stderr
,"usage: tcp_client <hostname> [port]\n");
38 if ((he
= gethostbyname(argv
[1])) == NULL
) {
40 perror("gethostbyname");
44 if ((sockfd
= socket(AF_INET
, SOCK_STREAM
, 0)) == -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) {
64 if ((numBytes
= recv(sockfd
, buffer
, sizeof(buffer
) - 1, 0)) == -1) {
67 // want the read thread to stay alive
71 buffer
[numBytes
] = '\0';
77 if (fgets(buffer
, sizeof(buffer
) - 1, stdin
) == NULL
) {
82 if ((send(sockfd
, buffer
, strlen(buffer
), 0)) == -1) {