2 gcc kqclient.c -o kqclient -Wall -W -Wextra -ansi -pedantic */
4 #include <netinet/in.h>
6 #include <sys/socket.h>
16 /* function prototypes */
17 void diep(const char *s
);
18 int tcpopen(const char *host
, int port
);
19 void sendbuftosck(int sckfd
, const char *buf
, int len
);
21 int main(int argc
, char *argv
[])
23 struct kevent chlist
[2]; /* events we want to monitor */
24 struct kevent evlist
[2]; /* events that were triggered */
26 int sckfd
, kq
, nev
, i
;
28 /* check argument count */
30 fprintf(stderr
, "usage: %s host port\n", argv
[0]);
34 /* open a connection to a host:port pair */
35 sckfd
= tcpopen(argv
[1], atoi(argv
[2]));
37 /* create a new kernel event queue */
38 if ((kq
= kqueue()) == -1)
41 /* initialise kevent structures */
42 EV_SET(&chlist
[0], sckfd
, EVFILT_READ
, EV_ADD
| EV_ENABLE
, 0, 0, 0);
43 EV_SET(&chlist
[1], fileno(stdin
), EVFILT_READ
, EV_ADD
| EV_ENABLE
, 0, 0, 0);
47 nev
= kevent(kq
, chlist
, 2, evlist
, 2, NULL
);
53 if (evlist
[0].flags
& EV_EOF
) /* read direction of socket has shutdown */
56 for (i
= 0; i
< nev
; i
++) {
57 if (evlist
[i
].flags
& EV_ERROR
) { /* report errors */
58 fprintf(stderr
, "EV_ERROR: %s\n", strerror(evlist
[i
].data
));
62 if (evlist
[i
].ident
== sckfd
) { /* we have data from the host */
63 memset(buf
, 0, BUFSIZE
);
64 if (read(sckfd
, buf
, BUFSIZE
) < 0)
69 else if (evlist
[i
].ident
== fileno(stdin
)) { /* we have data from stdin */
70 memset(buf
, 0, BUFSIZE
);
71 fgets(buf
, BUFSIZE
, stdin
);
72 sendbuftosck(sckfd
, buf
, strlen(buf
));
82 void diep(const char *s
)
88 int tcpopen(const char *host
, int port
)
90 struct sockaddr_in server
;
94 if ((hp
= gethostbyname(host
)) == NULL
)
95 diep("gethostbyname()");
97 if ((sckfd
= socket(PF_INET
, SOCK_STREAM
, 0)) < 0)
100 server
.sin_family
= AF_INET
;
101 server
.sin_port
= htons(port
);
102 server
.sin_addr
= *((struct in_addr
*)hp
->h_addr
);
103 memset(&(server
.sin_zero
), 0, 8);
105 if (connect(sckfd
, (struct sockaddr
*)&server
, sizeof(struct sockaddr
)) < 0)
111 void sendbuftosck(int sckfd
, const char *buf
, int len
)
117 if ((bytessent
= send(sckfd
, buf
+ pos
, len
- pos
, 0)) < 0)
120 } while (bytessent
> 0);