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
38 * There are, in effect, two different implementations here. One
39 * uses read(2) and write(2) directly with no buffering, the other
40 * uses stdio with line buffering (for better throughput). Both
41 * are known to work under Linux.
43 /* #define USE_STDIO */
47 * Size of buffer for internal buffering read function
48 * don't increase beyond the maximum atomic read/write size for
49 * your sockets, or you'll take a potentially huge performance hit
51 #define INTERNAL_BUFSIZE 2048
52 #endif /* USE_STDIO */
54 FILE *SockOpen(char *host, int clientPort)
58 struct sockaddr_in ad;
62 #endif /* USE_STDIO */
64 memset(&ad, 0, sizeof(ad));
65 ad.sin_family = AF_INET;
67 inaddr = inet_addr(host);
68 if (inaddr != INADDR_NONE)
69 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
72 hp = gethostbyname(host);
75 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
77 ad.sin_port = htons(clientPort);
79 sock = socket(AF_INET, SOCK_STREAM, 0);
82 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
89 return fdopen(sock, "r+");
91 fp = fdopen(sock, "r+");
93 setvbuf(fp, NULL, _IOLBF, INTERNAL_BUFSIZE);
96 #endif /* USE_STDIO */
100 #if defined(HAVE_STDARG_H)
101 int SockPrintf(FILE *sockfp, char* format, ...)
104 int SockPrintf(sockfp,format,va_alist)
113 #if defined(HAVE_STDARG_H)
114 va_start(ap, format) ;
118 vsprintf(buf, format, ap);
120 return SockWrite(buf, 1, strlen(buf), sockfp);
126 int SockWrite(char *buf, int size, int len, FILE *sockfp)
133 n = write(fileno(sockfp), buf, len);
143 char *SockGets(char *buf, int len, FILE *sockfp)
150 if (read(fileno(sockfp), cp, 1) != 1)
151 return((char *)NULL);
163 int SockWrite(char *buf, int size, int len, FILE *sockfp)
165 return(fwrite(buf, size, len, sockfp));
168 char *SockGets(char *buf, int len, FILE *sockfp)
170 return(fgets(buf, len, sockfp));
177 * Use the chargen service to test buffering directly.
181 FILE *fp = SockOpen("localhost", 19);
184 while (SockGets(buf, sizeof(buf)-1, fp))
185 SockWrite(buf, 1, strlen(buf), stdout);
189 /* socket.c ends here */