60#include <sys/socket.h>
61#include <netinet/in.h>
67void error_exit(
const char *msg) {
73int process_command(
char *buffer,
int sockfd) {
76 n = write(sockfd, buffer, strlen(buffer));
78 error_exit(
"ERROR writing to socket");
80 memset(buffer, 0, BUFLEN);
81 n = read(sockfd, buffer, BUFLEN - 1);
83 error_exit(
"ERROR reading from socket");
85 printf(
"%s\n", buffer);
90int main(
int argc,
char *argv[]) {
91 int sockfd, portno, arg_index;
92 struct sockaddr_in serv_addr;
93 struct hostent *server;
99 fprintf(stderr,
"Usage: %s hostname port [<command> [<command> ...]]\n", argv[0]);
103 portno = atoi(argv[2]);
104 sockfd = socket(AF_INET, SOCK_STREAM, 0);
106 error_exit(
"ERROR opening socket");
108 server = gethostbyname(argv[1]);
109 if (server == NULL) {
110 fprintf(stderr,
"ERROR, no such host\n");
114 memset(&serv_addr, 0,
sizeof(serv_addr));
115 serv_addr.sin_family = AF_INET;
116 memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length);
117 serv_addr.sin_port = htons(portno);
119 if (connect(sockfd, (
struct sockaddr *)&serv_addr,
sizeof(serv_addr)) < 0)
120 error_exit(
"ERROR connecting");
122 for (arg_index = 3; persist && arg_index < argc; arg_index++) {
123 if (snprintf(buffer, BUFLEN,
"%s\n", argv[arg_index]) >= BUFLEN) {
124 fprintf(stderr,
"ERROR: Command too long\n");
128 if (strcmp(buffer,
"disconnect\n") == 0)
131 printf(
"Processing command: %s", buffer);
134 process_command(buffer, sockfd);
138 printf(
"Please enter the message: ");
141 memset(buffer, 0, BUFLEN);
142 if (fgets(buffer, BUFLEN - 1, stdin) == NULL)
145 if (strcmp(buffer,
"disconnect\n") == 0)
148 process_command(buffer, sockfd);