7 #include <sys/socket.h>
8 #include <netinet/in.h>
13 int open_socket_out(char *host, int port)
15 int type = SOCK_STREAM;
16 struct sockaddr_in sock_out;
20 res = socket(PF_INET, type, 0);
25 hp = gethostbyname(host);
27 fprintf(stderr,"unknown host: %s\n", host);
32 memcpy(&sock_out.sin_addr, hp->h_addr, hp->h_length);
33 sock_out.sin_port = htons(port);
34 sock_out.sin_family = PF_INET;
36 if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))) {
37 fprintf(stderr,"failed to connect to %s - %s\n", host, strerror(errno));
46 static int open_socket_in(int type, int port, struct in_addr *address)
49 struct sockaddr_in sock;
54 /* get my host name */
55 if (gethostname(host_name, sizeof(host_name)) == -1) {
56 fprintf(stderr,"gethostname failed\n");
61 if ((hp = gethostbyname(host_name)) == 0) {
62 fprintf(stderr,"gethostbyname: Unknown host %s\n",host_name);
66 memset((char *)&sock,0,sizeof(sock));
67 memcpy((char *)&sock.sin_addr,(char *)hp->h_addr, hp->h_length);
68 sock.sin_port = htons(port);
69 sock.sin_family = hp->h_addrtype;
71 sock.sin_addr = *address;
73 sock.sin_addr.s_addr = INADDR_ANY;
75 res = socket(hp->h_addrtype, type, 0);
77 fprintf(stderr,"socket failed\n");
81 setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
83 /* now we've got a socket - we need to bind it */
84 if (bind(res, (struct sockaddr * ) &sock,sizeof(sock)) == -1) {
85 fprintf(stderr,"bind failed on port %d\n", port);
93 void set_nonblocking(int fd)
95 unsigned v = fcntl(fd, F_GETFL, 0);
96 fcntl(fd, F_SETFL, v | O_NONBLOCK);
99 static void child(int fd_in)
102 struct sockaddr addr;
103 int in_addrlen = sizeof(addr);
105 if (listen(fd_in, 5) == -1) {
110 fd = accept(fd_in,&addr,&in_addrlen);
116 static void parent(void)
118 int fd = open_socket_out("localhost", PORT);
128 if (select(8, NULL, &fset, NULL, NULL) == 1) {
129 if (write(fd, &c, 1) == -1 &&
130 (errno == EAGAIN || errno == EWOULDBLOCK)) {
131 printf("select returns when write would block\n");
135 if (count % 1024 == 0) {
136 printf("%d\n", count);
147 fd_in = open_socket_in(SOCK_STREAM, PORT, NULL);
149 fork() ? parent() : child(fd_in);