"Fossies" - the Fresh Open Source Software Archive 
As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style:
standard) with prefixed line numbers and
code folding option.
Alternatively you can here
view or
download the uninterpreted source code file.
1 #include "util.h"
2
3 #include <sys/socket.h>
4 #include <netdb.h>
5 #include <arpa/inet.h>
6 #include <netinet/in.h>
7 #include <unistd.h>
8
9 #include <stdlib.h>
10 #include <string.h>
11
12 static int resolve(const char *host, struct in_addr *saddr) {
13 struct hostent *hent;
14
15 if(inet_aton(host, saddr))
16 return 0;
17
18 hent = gethostbyname(host);
19 if(!hent)
20 return -1;
21
22 memcpy(saddr, hent->h_addr_list[0], sizeof(struct in_addr));
23 return 0;
24 }
25
26 int util_iconnect(const char *host, unsigned short port) {
27 int fd;
28 struct sockaddr_in s;
29
30 memset(&s, 0, sizeof(s));
31 s.sin_family = AF_INET;
32 if(resolve(host, &s.sin_addr) < 0)
33 return -2;
34 s.sin_port = htons(port);
35
36 fd = socket(AF_INET, SOCK_STREAM, 0);
37 if(fd < 0)
38 return -1;
39
40 if(connect(fd, (struct sockaddr *)&s, sizeof(s)) < 0) {
41 close(fd);
42 return -1;
43 }
44
45 return fd;
46 }
47
48 pid_t util_pipeto(char * const cmd[], int *read, int *write) {
49 int tochild[2];
50 int fromchild[2];
51 pid_t pid;
52
53 if(pipe(tochild) < 0)
54 return 0;
55 if(pipe(fromchild) < 0) {
56 close(tochild[0]);
57 close(tochild[1]);
58 return 0;
59 }
60
61 pid = fork();
62 if(pid < 0) {
63 close(tochild[0]);
64 close(tochild[1]);
65 close(fromchild[0]);
66 close(fromchild[1]);
67 return 0;
68 }
69
70 else if(pid == 0) {
71 close(tochild[1]);
72 close(fromchild[0]);
73 if(dup2(tochild[0], 0) < 0)
74 exit(1);
75 if(dup2(fromchild[1], 1) < 0)
76 exit(1);
77 if(execvp(cmd[0], cmd) < 0)
78 exit(1);
79 }
80
81 close(tochild[0]);
82 close(fromchild[1]);
83 *read = fromchild[0];
84 *write = tochild[1];
85
86 return pid;
87 }
88
89 void util_chomp(char *buf) {
90 char *p;
91
92 p = buf + strlen(buf) - 1;
93 if(*p == '\n') {
94 *p-- = '\0';
95 if(*p == '\r')
96 *p = '\0';
97 }
98 }
99
100 int util_split(const char *delim, char *buf, char **resp, int max) {
101 int count;
102 char *p;
103
104 if(max < 1)
105 return 0;
106
107 if(!*buf) {
108 resp[0] = NULL;
109 return 0;
110 }
111
112 count = 1;
113 resp[0] = p = buf;
114
115 while(*p) {
116 if(count >= max)
117 return count;
118 if(strchr(delim, *p)) {
119 do {
120 *p++ = '\0';
121 } while(*p && strchr(delim, *p));
122 if(*p)
123 resp[count++] = p;
124 }
125 else
126 p++;
127 }
128 return count;
129 }