-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcpcli.c
77 lines (69 loc) · 1.97 KB
/
tcpcli.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
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
// #define SRVPORT "49154"
struct msg_echo {
unsigned short seq;
unsigned short reserve;
char msg[32];
};
int main(int argc, char *argv[])
{
int sd, err, cnt;
struct addrinfo hints, *res;
struct msg_echo echo;
if (argc != 3) {
fprintf(stderr, "Usage: ./tcpcli <IP address> <port number>\n");
exit(1);
}
memset(&hints, 0, sizeof hints);
hints.ai_socktype = SOCK_STREAM;
if ((err = getaddrinfo(argv[1], argv[2], &hints, &res)) < 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(err));
exit(1);
}
if ((sd = socket(res->ai_family, res->ai_socktype,
res->ai_protocol)) < 0) {
perror("socket");
exit(1);
}
if (connect(sd, res->ai_addr, res->ai_addrlen) < 0) {
perror("connect");
exit(1);
}
freeaddrinfo(res);
for (;;) {
printf("message to be sent (FIN to exit): ");
if (fgets(echo.msg, sizeof echo.msg, stdin) == NULL) {
break;
}
echo.msg[strlen(echo.msg) - 1] = '\0';
if (!strcmp(echo.msg, "FIN")) {
printf("FIN received from client\n");
break;
} else if (echo.seq == 10) {
printf("Finished: seq = 10\n");
break;
}
if ((cnt = send(sd, &echo, sizeof echo, 0)) < 0) {
perror("send");
exit(1);
}
printf("%d bytes sent\n", cnt);
if ((cnt = recv(sd, &echo, sizeof echo, 0)) < 0) {
perror("recv");
exit(1);
}
echo.msg[cnt - sizeof(unsigned short) * 2] = '\0';
printf("%d bytes recved: IP %s, port %s, seq %d, msg %s\n",
cnt, argv[1], argv[2], echo.seq, echo.msg);
}
close(sd);
}