Repository navigation
Expand file tree
/
Copy pathclient.c
More file actions
88 lines (76 loc) · 1.8 KB
/
Copy pathclient.c
File metadata and controls
88 lines (76 loc) · 1.8 KB
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
80
81
82
83
84
85
86
87
88
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "utility.c"
#include "main.h"
int main(int argc, char *argv[])
{
int socket_fd;
struct sockaddr_in servaddr;
char *host;
int port_number;
if (argc < 2)
{
fprintf(stderr, "usage: %s host [server_port_n]\n", argv[0]);
exit(1);
}
host = argv[1];
if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
unix_error("Socket Creation Failed");
}
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(host);
//Set port for server if specified
if (argv[2] != NULL)
{
port_number = atoi(argv[2]);
}
else
{
port_number = DEFAULT_PORT;
}
servaddr.sin_port = htons(port_number);
//Call connect to establish connection with server (servaddr)
if (connect(socket_fd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1)
{
unix_error("Connection with the server failed..");
}
printf("Connected to server..\n");
printf("Response from server:\n");
char message[MAX_LINE];
read(socket_fd, message, sizeof(message));
printf("%s", message);
handle_client_request_response(socket_fd);
close(socket_fd);
}
void handle_client_request_response(int socket_fd)
{
char buff[MAX_LINE];
int n;
while (1)
{
//Get client input
bzero(buff, sizeof(buff));
n = 0;
while ((buff[n++] = getchar()) != '\n')
;
//Send client input
write(socket_fd, buff, sizeof(buff));
if ((int)buff[0] == 27)
{
printf("Client exiting...\n");
break;
}
bzero(buff, sizeof(buff));
//Read response from server
read(socket_fd, buff, sizeof(buff));
printf("Response form server : %s", buff);
}
}