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
37 FILE *SockOpen(char *host, int clientPort)
41 struct sockaddr_in ad;
44 memset(&ad, 0, sizeof(ad));
45 ad.sin_family = AF_INET;
47 inaddr = inet_addr(host);
48 if (inaddr != INADDR_NONE)
49 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
52 hp = gethostbyname(host);
55 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
57 ad.sin_port = htons(clientPort);
59 sock = socket(AF_INET, SOCK_STREAM, 0);
62 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
68 return fdopen(sock, "r+");
72 #if defined(HAVE_STDARG_H)
73 int SockPrintf(FILE *sockfp, char* format, ...)
76 int SockPrintf(sockfp,format,va_alist)
85 #if defined(HAVE_STDARG_H)
86 va_start(ap, format) ;
90 vsprintf(buf, format, ap);
92 return SockWrite(buf, 1, strlen(buf), sockfp);
96 int SockWrite(char *buf, int size, int len, FILE *sockfp)
103 n = write(fileno(sockfp), buf, len);
113 char *SockGets(char *buf, int len, FILE *sockfp)
121 if ((n = recv(fileno(sockfp), bp, len, MSG_PEEK)) == -1)
123 if ((p = memchr(bp, '\n', n)) != NULL)
125 if (read(fileno(sockfp), bp, ++p - bp) == -1)
130 if ((n = read(fileno(sockfp), bp, n)) == -1)
141 * Use the chargen service to test input beuffering directly.
142 * You may have to uncomment the `chargen' service description in your
143 * inetd.conf (and then SIGHUP inetd) for this to work.
147 FILE *fp = SockOpen("localhost", 19);
150 while (SockGets(buf, sizeof(buf)-1, fp))
151 SockWrite(buf, 1, strlen(buf), stdout);
155 /* socket.c ends here */