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)
29 #ifdef INADDR_BROADCAST
30 #define INADDR_NONE INADDR_BROADCAST
32 #define INADDR_NONE -1
40 int SockOpen(char *host, int clientPort)
44 struct sockaddr_in ad;
47 memset(&ad, 0, sizeof(ad));
48 ad.sin_family = AF_INET;
50 inaddr = inet_addr(host);
51 if (inaddr != INADDR_NONE)
52 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
55 hp = gethostbyname(host);
58 * Add a check to make sure the address has a valid IPv4 or IPv6
59 * length. This prevents buffer spamming by a broken DNS.
61 if (hp == NULL || (hp->h_length != 4 && hp->h_length != 8))
64 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
66 ad.sin_port = htons(clientPort);
68 sock = socket(AF_INET, SOCK_STREAM, 0);
71 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
81 #if defined(HAVE_STDARG_H)
82 int SockPrintf(int sock, char* format, ...)
85 int SockPrintf(sock,format,va_alist)
94 #if defined(HAVE_STDARG_H)
95 va_start(ap, format) ;
100 vsnprintf(buf, sizeof(buf), format, ap);
102 vsprintf(buf, format, ap);
105 return SockWrite(sock, buf, strlen(buf));
109 int SockWrite(int sock, char *buf, int len)
115 n = write(sock, buf, len);
125 int SockRead(int sock, char *buf, int len)
127 char *newline, *bp = buf;
134 * The reason for these gymnastics is that we want two things:
135 * (1) to read \n-terminated lines,
136 * (2) to return the true length of data read, even if the
137 * data coming in has embedded NULS.
139 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
141 if ((newline = memchr(bp, '\n', n)) != NULL)
142 n = newline - bp + 1;
143 if ((n = read(sock, bp, n)) == -1)
153 int SockPeek(int sock)
154 /* peek at the next socket character without actually reading it */
159 if ((n = recv(sock, &ch, 1, MSG_PEEK)) == -1)
167 * Use the chargen service to test input beuffering directly.
168 * You may have to uncomment the `chargen' service description in your
169 * inetd.conf (and then SIGHUP inetd) for this to work.
173 int sock = SockOpen("localhost", 19);
176 while (SockRead(sock, buf, sizeof(buf)-1))
177 SockWrite(1, buf, strlen(buf));
181 /* socket.c ends here */