2 * socket.c -- socket library functions
4 * These were designed and coded by Carl Harris <ceharris@mal.com>
5 * and are essentially unchanged from the ancestral popclient.
7 * The file pointer arguments are currently misleading -- there
8 * is only one shared internal buffer for all sockets.
10 * For license terms, see the file COPYING in this directory.
17 #include <sys/types.h>
18 #include <sys/socket.h>
19 #include <netinet/in.h>
20 #include <arpa/inet.h>
23 #include <sys/ioctl.h>
24 #if defined(STDC_HEADERS)
28 #if defined(HAVE_UNISTD_H)
31 #if defined(HAVE_STDARG_H)
39 /* Size of buffer for internal buffering read function
40 don't increase beyond the maximum atomic read/write size for
41 your sockets, or you'll take a potentially huge performance hit */
43 #define INTERNAL_BUFSIZE 2048
45 FILE *Socket(host, clientPort)
51 struct sockaddr_in ad;
54 memset(&ad, 0, sizeof(ad));
55 ad.sin_family = AF_INET;
57 inaddr = inet_addr(host);
58 if (inaddr != INADDR_NONE)
59 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
62 hp = gethostbyname(host);
65 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
67 ad.sin_port = htons(clientPort);
69 sock = socket(AF_INET, SOCK_STREAM, 0);
72 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
74 return fdopen(sock, "r+");
77 int SockWrite(buf,len,sockfp)
86 n = write(fileno(sockfp), buf, len);
96 static int sbuflen = 0;
98 static int SockInternalRead (socket,buf,len)
103 static char sbuf [INTERNAL_BUFSIZE];
107 /* buffer is empty; refresh. */
108 if ((sbuflen = read(socket,sbuf,INTERNAL_BUFSIZE)) < 0) {
111 perror("SockInternalRead: read");
118 ; /* already some data in the buffer */
120 /* can't get more than we have right now. */
121 /* XXX -- should probably try to load any unused part of sbuf
122 so that as much of 'len' as possible can be satisfied */
126 ; /* wants no more than we already have */
128 /* transfer to caller's buffer */
130 /* special case: if caller only wants one character, it probably
131 costs a lot more to call bcopy than to do it ourselves. */
143 int SockGets(buf, len, sockfp)
152 if (SockInternalRead(fileno(sockfp), buf, 1) != 1)
158 if (*buf != '\r') /* remove all CRs */
165 #if defined(HAVE_STDARG_H)
166 int SockPrintf(FILE *sockfp, char* format, ...)
169 int SockPrintf(sockfp,format,va_alist)
178 #if defined(HAVE_STDARG_H)
179 va_start(ap, format) ;
183 vsprintf(buf, format, ap);
185 return SockWrite(buf, strlen(buf), sockfp);
189 /* socket.c ends here */