remoteinfo.c (1865B)
1 #include "remoteinfo.h" 2 3 #include <sys/types.h> 4 #include <sys/socket.h> 5 #include <netinet/in.h> 6 #include <fcntl.h> 7 #include <unistd.h> 8 #include "byte.h" 9 #include "substdio.h" 10 #include "ip.h" 11 #include "fmt.h" 12 #include "timeoutconn.h" 13 #include "timeoutread.h" 14 #include "timeoutwrite.h" 15 16 static char line[999]; 17 static int t; 18 19 static ssize_t mywrite(int fd, const void *buf, size_t len) 20 { 21 return timeoutwrite(t,fd,buf,len); 22 } 23 static ssize_t myread(int fd, void *buf, size_t len) 24 { 25 return timeoutread(t,fd,buf,len); 26 } 27 28 char *remoteinfo_get(ipr,rp,ipl,lp,timeout) 29 struct ip_address *ipr; 30 unsigned long rp; 31 struct ip_address *ipl; 32 unsigned long lp; 33 int timeout; 34 { 35 char *x; 36 int s; 37 struct sockaddr_in sin; 38 substdio ss; 39 char buf[32]; 40 unsigned int len; 41 int numcolons; 42 char ch; 43 44 t = timeout; 45 46 s = socket(AF_INET,SOCK_STREAM,0); 47 if (s == -1) return 0; 48 49 byte_zero(&sin,sizeof(sin)); 50 sin.sin_family = AF_INET; 51 byte_copy(&sin.sin_addr,4,ipl); 52 sin.sin_port = 0; 53 if (bind(s,(struct sockaddr *) &sin,sizeof(sin)) == -1) { close(s); return 0; } 54 if (timeoutconn(s,ipr,113,timeout) == -1) { close(s); return 0; } 55 fcntl(s,F_SETFL,fcntl(s,F_GETFL,0) & ~O_NDELAY); 56 57 len = 0; 58 len += fmt_ulong(line + len,rp); 59 len += fmt_str(line + len," , "); 60 len += fmt_ulong(line + len,lp); 61 len += fmt_str(line + len,"\r\n"); 62 63 substdio_fdbuf(&ss,mywrite,s,buf,sizeof(buf)); 64 if (substdio_putflush(&ss,line,len) == -1) { close(s); return 0; } 65 66 substdio_fdbuf(&ss,myread,s,buf,sizeof(buf)); 67 x = line; 68 numcolons = 0; 69 for (;;) { 70 if (substdio_get(&ss,&ch,1) != 1) { close(s); return 0; } 71 if ((ch == ' ') || (ch == '\t') || (ch == '\r')) continue; 72 if (ch == '\n') break; 73 if (numcolons < 3) { if (ch == ':') ++numcolons; } 74 else { *x++ = ch; if (x == line + sizeof(line) - 1) break; } 75 } 76 *x = 0; 77 close(s); 78 return line; 79 }