-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathWebClient.c
67 lines (61 loc) · 1.44 KB
/
WebClient.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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
int main(int argc, char const *argv[])
{
if (argc != 3)
{
printf("usage : %s <#ip> <#port>\n", argv[0]);
exit(1);
}
int fd;
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket error");
exit(1);
}
struct sockaddr_in svraddr;
bzero(&svraddr, sizeof(svraddr));
svraddr.sin_family = AF_INET;
svraddr.sin_port = htons(atoi(argv[2]));
if (inet_pton(AF_INET, argv[1], &svraddr.sin_addr) < 0)
{
perror("inet_pton error");
exit(1);
}
if (connect(fd, (struct sockaddr *)&svraddr, sizeof(svraddr)) < 0)
{
perror("connect error");
exit(1);
}
printf("connnect succ!\n");
ssize_t ntowrite = 0;
char buf[1024];
while (fgets(buf, sizeof(buf), stdin) != NULL)
{
ntowrite = strlen(buf);
if (buf[ntowrite - 1] == '\n')
{
buf[ntowrite - 1] = 0;
ntowrite--;
}
write(fd, buf, ntowrite);
printf("client begin to receive\n");
ssize_t nread = read(fd, buf, sizeof(buf));
buf[nread] = 0;
if (fputs(buf, stdout) == EOF)
{
printf("fputs error!\n");
exit(1);
}
}
if (ferror(stdin))
{
printf("fgets error");
exit(1);
}
return 0;
}