1 #include <netinet/in.h>
3 #include <sys/socket.h>
13 /* function prototypes */
14 void diep(const char *s
);
15 int tcpopen(const char *host
, int port
);
16 void sendbuftosck(int sckfd
, const char *buf
, int len
);
18 int main(int argc
, char *argv
[])
20 struct kevent chlist
[2]; /* events we want to monitor */
21 struct kevent evlist
[2]; /* events that were triggered */
23 int sckfd
, kq
, nev
, i
;
25 /* check argument count */
27 fprintf(stderr
, "usage: %s host port\n", argv
[0]);
31 /* open a connection to a host:port pair */
32 sckfd
= tcpopen(argv
[1], atoi(argv
[2]));
34 /* create a new kernel event queue */
35 if ((kq
= kqueue()) == -1)
38 /* initialise kevent structures */
39 EV_SET(&chlist
[0], sckfd
, EVFILT_READ
, EV_ADD
| EV_ENABLE
, 0, 0, 0);
40 EV_SET(&chlist
[1], fileno(stdin
), EVFILT_READ
, EV_ADD
| EV_ENABLE
, 0, 0, 0);
44 nev
= kevent(kq
, chlist
, 2, evlist
, 2, NULL
);
50 if (evlist
[0].flags
& EV_EOF
) /* read direction of socket has shutdown */
53 for (i
= 0; i
< nev
; i
++) {
54 if (evlist
[i
].flags
& EV_ERROR
) { /* report errors */
55 fprintf(stderr
, "EV_ERROR: %s\n", strerror(evlist
[i
].data
));
59 if (evlist
[i
].ident
== sckfd
) { /* we have data from the host */
60 memset(buf
, 0, BUFSIZE
);
61 if (read(sckfd
, buf
, BUFSIZE
) < 0)
66 else if (evlist
[i
].ident
== fileno(stdin
)) { /* we have data from stdin */
67 memset(buf
, 0, BUFSIZE
);
68 fgets(buf
, BUFSIZE
, stdin
);
69 sendbuftosck(sckfd
, buf
, strlen(buf
));
79 void diep(const char *s
)
85 int tcpopen(const char *host
, int port
)
87 struct sockaddr_in server
;
91 if ((hp
= gethostbyname(host
)) == NULL
)
92 diep("gethostbyname()");
94 if ((sckfd
= socket(PF_INET
, SOCK_STREAM
, 0)) < 0)
97 server
.sin_family
= AF_INET
;
98 server
.sin_port
= htons(port
);
99 server
.sin_addr
= *((struct in_addr
*)hp
->h_addr
);
100 memset(&(server
.sin_zero
), 0, 8);
102 if (connect(sckfd
, (struct sockaddr
*)&server
, sizeof(struct sockaddr
)) < 0)
108 void sendbuftosck(int sckfd
, const char *buf
, int len
)
114 if ((bytessent
= send(sckfd
, buf
+ pos
, len
- pos
, 0)) < 0)
117 } while (bytessent
> 0);