-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpcli01.c
81 lines (72 loc) · 1.47 KB
/
tcpcli01.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
#include "unp.h"
#include "apueerror.h"
static int read_cnt;
static char *read_ptr;
static char read_buf[MAXLINE];
int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr;
if(argc != 2)
err_quit("Usage: tcpcli <IPaddress>");
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
printf("start connecting...\n");
connect(sockfd, (SA *)&servaddr, sizeof(servaddr));
str_cli(stdin, sockfd);
exit(0);
}
void str_cli(FILE *fp, int sockfd)
{
char sendline[MAXLINE],recvline[MAXLINE];
while(fgets(sendline, MAXLINE, fp)!=NULL)
{
write(sockfd, sendline, strlen(sendline));
if(readline(sockfd, recvline, MAXLINE) == 0)
err_quit("str_cli: server terminated prematurely");
fputs(recvline, stdout);
}
}
static ssize_t my_read(int fd, char *ptr)
{
if(read_cnt <= 0)
{
again1:
if((read_cnt = read(fd, read_buf, sizeof(read_buf))) < 0)
{
if(errno == EINTR)
goto again1;
return (-1);
}else if (read_cnt == 0)
return(0);
read_ptr = read_buf;
}
read_cnt--;
*ptr = *read_ptr++;
return(1);
}
ssize_t readline(int fd, void *vptr, size_t maxlen)
{
ssize_t n,rc;
char c,*ptr;
ptr = vptr;
for(n=1;n<maxlen;n++)
{
if((rc = my_read(fd, &c)) == 1)
{
*ptr++ = c;
if(c=='\n')
break;
}else if (rc == 0)
{
*ptr = 0;
return (n-1);
}else
return (-1);
}
*ptr = 0;
return (n);
}