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 *Socket(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)
67 return fdopen(sock, "r+");
71 #if defined(HAVE_STDARG_H)
72 int SockPrintf(FILE *sockfp, char* format, ...)
75 int SockPrintf(sockfp,format,va_alist)
84 #if defined(HAVE_STDARG_H)
85 va_start(ap, format) ;
89 vsprintf(buf, format, ap);
91 return SockWrite(buf, strlen(buf), sockfp);
96 * FIXME: This needs to be recoded to use stdio, if that's possible.
98 * If you think these functions are too slow and inefficient, you're
99 * absolutely right. I wish I could figure out what to do about it.
100 * The ancestral popclient used static buffering here to cut down on the
101 * number of read(2) calls, but we can't do that because we can have
102 * two or more sockets open at a time.
104 * The right thing to do would be to use stdio for internal per-socket
105 * buffering here (which is why Socket() returns a file pointer) but
106 * this causes mysterious lossage. In case someone ever finds a way
107 * around this, a note on Carl Harris's original implementation said:
109 * Size of buffer for internal buffering read function
110 * don't increase beyond the maximum atomic read/write size for
111 * your sockets, or you'll take a potentially huge performance hit
113 * #define INTERNAL_BUFSIZE 2048
117 int SockWrite(char *buf, int len, FILE *sockfp)
123 n = write(fileno(sockfp), buf, len);
133 int SockGets(char *buf, int len, FILE *sockfp)
139 if (read(fileno(sockfp), buf, 1) != 1)
145 if (*buf != '\r') /* remove all CRs */
152 /* socket.c ends here */