-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.c
113 lines (85 loc) · 2.84 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include<arpa/inet.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#define READ_BUFFER_SIZE 10
int connect_to_server(char*,char*);
void read_and_write(int);
int main(int argc,char *argv[]){
if(argc != 3)
{
printf("\nCorrect usage is ./%s <server-ip address> <port number>\n", argv[0]);
exit(EXIT_FAILURE);
}
/* connect to server */
int csfd = connect_to_server(argv[1], argv[2]);
/* write to the client and read back the reversed string from server, and print the same on standard output.*/
read_and_write(csfd);
/* close the socket descriptors for client. */
close(csfd);
}
int connect_to_server(char *ip_addr, char *port_no){
struct addrinfo hints;
struct addrinfo *result, *rp;
int sfd, ret;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; /* Only want IPv4 (use AF_INET6 for IPv6) */
hints.ai_socktype = SOCK_STREAM; /* Only want stream-based connection */
ret = getaddrinfo(ip_addr, port_no, &hints, &result);
if (ret != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret));
exit(EXIT_FAILURE);
}
/* getaddrinfo() returns a list of address structures.
Try each address until we successfully connect(2).
If socket(2) (or connect(2)) fails, we (close the socket
and) try the next address. */
for (rp = result; rp != NULL; rp = rp->ai_next){
sfd = socket(rp->ai_family, rp->ai_socktype,rp->ai_protocol);
if (sfd == -1){
continue;
}
if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1){
break; /* Success */
}
close(sfd);
}
if (rp == NULL){ /* No address succeeded */
fprintf(stderr, "Could not connect\n");
exit(EXIT_FAILURE);
}
freeaddrinfo(result);
return sfd;
}
void read_and_write(int csfd){
FILE *fd;
int size=0;
int i = 0, nbytes;
char *buff = malloc(0);
char *temp_buff = buff;
do{
printf("\nEnter the string you want to send to the server!!\n");
i++;
buff = realloc(buff,READ_BUFFER_SIZE*i);
temp_buff = buff + READ_BUFFER_SIZE*(i-1);
nbytes = read(STDIN_FILENO,temp_buff,READ_BUFFER_SIZE); //STDIN_FILENO:- <unistd.h> symbolic constant for standard-input fd.
size += nbytes;
}while(nbytes == READ_BUFFER_SIZE && temp_buff[nbytes-1]!='\n');
temp_buff[nbytes-1] = '\0';
fd = fdopen(csfd,"r+");
if(fd == NULL){
perror("fdopen failed!!");
exit(EXIT_FAILURE);
}
nbytes = fwrite(buff,1,size,fd);
fflush(fd);
fcntl(csfd,F_SETFL,O_NONBLOCK);
while((nbytes = fread(buff,1,size,fd))<=0);
buff[size] = '\0';
printf("\nReceived Message is:-\n%s\n",buff);
}