2 * socket.c -- socket library functions
4 * For license terms, see the file COPYING in this directory.
11 #include <sys/types.h>
12 #include <sys/socket.h>
13 #include <netinet/in.h>
14 #include <arpa/inet.h>
16 #if defined(STDC_HEADERS)
19 #if defined(HAVE_UNISTD_H)
22 #if defined(HAVE_STDARG_H)
30 #ifdef INADDR_BROADCAST
31 #define INADDR_NONE INADDR_BROADCAST
33 #define INADDR_NONE -1
41 FILE *SockOpen(char *host, int clientPort)
45 struct sockaddr_in ad;
48 memset(&ad, 0, sizeof(ad));
49 ad.sin_family = AF_INET;
51 inaddr = inet_addr(host);
52 if (inaddr != INADDR_NONE)
53 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
56 hp = gethostbyname(host);
59 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
61 ad.sin_port = htons(clientPort);
63 sock = socket(AF_INET, SOCK_STREAM, 0);
66 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
72 return fdopen(sock, "r+");
76 #if defined(HAVE_STDARG_H)
77 int SockPrintf(FILE *sockfp, char* format, ...)
80 int SockPrintf(sockfp,format,va_alist)
89 #if defined(HAVE_STDARG_H)
90 va_start(ap, format) ;
94 vsprintf(buf, format, ap);
96 return SockWrite(buf, 1, strlen(buf), sockfp);
100 int SockWrite(char *buf, int size, int len, FILE *sockfp)
107 n = write(fileno(sockfp), buf, len);
117 char *SockGets(char *buf, int len, FILE *sockfp)
125 /* return value of 0 is EOF, < 0 is error */
126 if ((n = recv(fileno(sockfp), bp, len, MSG_PEEK)) <= 0)
128 if ((p = memchr(bp, '\n', n)) != NULL)
130 if (read(fileno(sockfp), bp, ++p - bp) == -1)
135 if ((n = read(fileno(sockfp), bp, n)) == -1)
144 int SockPeek(FILE *sockfp)
145 /* peek at the next socket character without actually reading it */
150 if ((n = recv(fileno(sockfp), &ch, 1, MSG_PEEK)) == -1)
158 * Use the chargen service to test input beuffering directly.
159 * You may have to uncomment the `chargen' service description in your
160 * inetd.conf (and then SIGHUP inetd) for this to work.
164 FILE *fp = SockOpen("localhost", 19);
167 while (SockGets(buf, sizeof(buf)-1, fp))
168 SockWrite(buf, 1, strlen(buf), stdout);
172 /* socket.c ends here */