-
Notifications
You must be signed in to change notification settings - Fork 0
/
client3.c
116 lines (85 loc) · 2.56 KB
/
client3.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
114
115
116
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#define MAX_MSG_SIZE 1024
/*
* The function get_sockaddr converts the server's address and port into a form usable to create a
* socket
*/
struct addrinfo* get_sockaddr(const char* hostname, const char *port)
{
struct addrinfo hints;
struct addrinfo* results;
int rv;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; //Return socket address for the server's IPv4 addresses
hints.ai_socktype = SOCK_STREAM; //Return TCP socket addresses
/* Use getaddrinfo will get address information for the host specified by hostnae */
rv = getaddrinfo(hostname, port, &hints, &results);
if (rv != 0){
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
exit(1);
}
return results;
}
/*
* The function open_connection establishes a connection to the server
*/
int open_connection(struct addrinfo* addr_list)
{
struct addrinfo* p;
int sockfd;
//Iterate through each addr info in the list; Stop when we successully connect to one
for (p = addr_list; p != NULL; p = p->ai_next)
{
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
// Try the next address since the socket operation failed
if (sockfd == -1) continue;
//Stop iterating of we are able to connect to the server
if (connect(sockfd,p->ai_addr, p->ai_addrlen) != -1) break;
}
freeaddrinfo(addr_list);
if (p == NULL)
err(EXIT_FAILURE, "%s", "Unable to connect");
else
return sockfd;
}
int main(int argc, char *argv[])
{
int numbytes;
char sendBuff[MAX_MSG_SIZE];
char recvBuff[MAX_MSG_SIZE];
struct sockaddr_in serv_addr;
struct hostent *server;
int rv;
int a, b, sum;
if(argc != 3)
{
printf("\n Usage: %s hostname port \n",argv[0]);
return 1;
}
struct addrinfo* results = get_sockaddr(argv[1], argv[2]);
int sockfd = open_connection(results);
memset(sendBuff, '0',sizeof(sendBuff));
memset(recvBuff, '0',sizeof(recvBuff));
a = 5;
b = 10;
snprintf(sendBuff, sizeof(sendBuff), "%d %d", a,b);
write(sockfd, sendBuff, strlen(sendBuff));
numbytes = recv(sockfd,recvBuff,sizeof(recvBuff)-1,0);
if (numbytes == -1){
perror("recv");
exit(1);
}
recvBuff[numbytes] = '\0';
sscanf(recvBuff, "%d", &sum);
printf("received sum is %d\n", sum);
return 0;
}