2 * Misc network functions
10 int Read(int fd, unsigned char *buf, int len)
16 while ((i < len) && (!(i < 0)))
18 j = read(fd, &(buf[i]), len-i);
19 if ( (j < 0) && (errno != EAGAIN))
20 return -errno; /* fail */
26 * Reached maximum number of allowed read errors.
28 * Lets suppose the connection is lost and errno didn't
36 i += j; /* success, continue */
42 * Create a listener socket.
44 * We go out of our way to make this interesting. (The Easy Way is not
48 int establish(u_short portnum)
52 struct addrinfo hints, *res, *ressave;
55 sprintf(serv, "%d", portnum);
57 memset(&hints, 0, sizeof(struct addrinfo));
58 hints.ai_flags = AI_PASSIVE;
59 hints.ai_family = AF_UNSPEC;
60 hints.ai_socktype = SOCK_STREAM;
61 if (getaddrinfo(NULL/*any IP*/, serv, &hints, &res) != 0) {
62 perror("getaddrinfo");
68 listenfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
71 setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
72 if (bind(listenfd, res->ai_addr, res->ai_addrlen) == 0)
75 } while ( (res = res->ai_next) );
80 if (listen(listenfd, 1024)!=0) {
85 freeaddrinfo(ressave);
90 int get_connection(int s)
94 int t; /* socket of connection */
96 memset(&isa, 0, sizeof(struct sockaddr));
97 if ((t = accept(s,&isa,&addrlen)) < 0) {
105 int openconn(char *hostname, int port)
107 struct sockaddr_in sa;
111 if (!(hp = gethostbyname(hostname))) {
112 perror("gethostbyname");
116 memset(&sa.sin_zero, 0, 8);
117 sa.sin_port = htons(port);
118 memcpy(&sa.sin_addr, hp->h_addr, hp->h_length);
119 sa.sin_family = hp->h_addrtype;
121 ret = socket(hp->h_addrtype, SOCK_STREAM, 0);
122 if (connect(ret, (struct sockaddr *)&sa, sizeof(struct sockaddr_in))<0) {