2 * Misc network functions
8 int Read(int fd, unsigned char *buf, int len)
14 while ((i < len) && (!(i < 0)))
16 j = read(fd, &(buf[i]), len-i);
17 if ( (j < 0) && (errno != EAGAIN))
18 return -errno; /* fail */
24 * Reached maximum number of allowed read errors.
26 * Lets suppose the connection is lost and errno didn't
34 i += j; /* success, continue */
40 * Create a listener socket.
42 * We go out of our way to make this interesting. (The Easy Way is not
46 int establish(u_short portnum)
50 struct addrinfo hints, *res, *ressave;
53 sprintf(serv, "%d", portnum);
55 memset(&hints, 0, sizeof(struct addrinfo));
56 hints.ai_flags = AI_PASSIVE;
57 hints.ai_family = AF_UNSPEC;
58 hints.ai_socktype = SOCK_STREAM;
59 if (getaddrinfo(NULL/*any IP*/, serv, &hints, &res) != 0) {
60 perror("getaddrinfo");
66 listenfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
69 setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
70 if (bind(listenfd, res->ai_addr, res->ai_addrlen) == 0)
73 } while ( (res = res->ai_next) );
78 if (listen(listenfd, 1024)!=0) {
83 freeaddrinfo(ressave);
88 int get_connection(int s)
92 int t; /* socket of connection */
94 memset(&isa, 0, sizeof(struct sockaddr));
95 if ((t = accept(s,&isa,&addrlen)) < 0) {
103 int openconn(char *hostname, int port)
105 struct sockaddr_in sa;
109 if (!(hp = gethostbyname(hostname))) {
110 perror("gethostbyname");
114 memset(&sa.sin_zero, 0, 8);
115 sa.sin_port = htons(port);
116 memcpy(&sa.sin_addr, hp->h_addr, hp->h_length);
117 sa.sin_family = hp->h_addrtype;
119 ret = socket(hp->h_addrtype, SOCK_STREAM, 0);
120 if (connect(ret, (struct sockaddr *)&sa, sizeof(struct sockaddr_in))<0) {