2 * socket.c -- socket library functions
4 * For license terms, see the file COPYING in this directory.
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <netinet/in.h>
13 #include <arpa/inet.h>
15 #if defined(STDC_HEADERS)
18 #if defined(HAVE_UNISTD_H)
21 #if defined(HAVE_STDARG_H)
30 #ifdef INADDR_BROADCAST
31 #define INADDR_NONE INADDR_BROADCAST
33 #define INADDR_NONE -1
36 #endif /* INET_ATON */
42 int SockOpen(char *host, int clientPort)
47 #endif /* INET_ATON */
48 struct sockaddr_in ad;
51 memset(&ad, 0, sizeof(ad));
52 ad.sin_family = AF_INET;
54 /* we'll accept a quad address */
56 inaddr = inet_addr(host);
57 if (inaddr != INADDR_NONE)
58 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
61 if (!inet_aton(host, &ad.sin_addr))
62 #endif /* INET_ATON */
64 hp = gethostbyname(host);
67 * Add a check to make sure the address has a valid IPv4 or IPv6
68 * length. This prevents buffer spamming by a broken DNS.
70 if (hp == NULL || (hp->h_length != 4 && hp->h_length != 8))
73 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
75 ad.sin_port = htons(clientPort);
77 sock = socket(AF_INET, SOCK_STREAM, 0);
80 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
90 #if defined(HAVE_STDARG_H)
91 int SockPrintf(int sock, char* format, ...)
94 int SockPrintf(sock,format,va_alist)
103 #if defined(HAVE_STDARG_H)
104 va_start(ap, format) ;
108 #ifdef HAVE_VSNPRINTF
109 vsnprintf(buf, sizeof(buf), format, ap);
111 vsprintf(buf, format, ap);
114 return SockWrite(sock, buf, strlen(buf));
118 int SockWrite(int sock, char *buf, int len)
124 n = write(sock, buf, len);
134 int SockRead(int sock, char *buf, int len)
136 char *newline, *bp = buf;
143 * The reason for these gymnastics is that we want two things:
144 * (1) to read \n-terminated lines,
145 * (2) to return the true length of data read, even if the
146 * data coming in has embedded NULS.
148 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
150 if ((newline = memchr(bp, '\n', n)) != NULL)
151 n = newline - bp + 1;
152 if ((n = read(sock, bp, n)) == -1)
162 int SockPeek(int sock)
163 /* peek at the next socket character without actually reading it */
168 if ((n = recv(sock, &ch, 1, MSG_PEEK)) == -1)
176 * Use the chargen service to test input beuffering directly.
177 * You may have to uncomment the `chargen' service description in your
178 * inetd.conf (and then SIGHUP inetd) for this to work.
182 int sock = SockOpen("localhost", 19);
185 while (SockRead(sock, buf, sizeof(buf)-1))
186 SockWrite(1, buf, strlen(buf));
190 /* socket.c ends here */