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 int 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)
76 #if defined(HAVE_STDARG_H)
77 int SockPrintf(int sock, char* format, ...)
80 int SockPrintf(sock,format,va_alist)
89 #if defined(HAVE_STDARG_H)
90 va_start(ap, format) ;
94 vsprintf(buf, format, ap);
96 return SockWrite(sock, buf, strlen(buf));
100 int SockWrite(int sock, char *buf, int len)
106 n = write(sock, buf, len);
116 int SockRead(int sock, char *buf, int len)
125 * The reason for these gymnastics is that we want two things:
126 * (1) to read \n-terminated lines,
127 * (2) to return the true length of data read, even if the
128 * data coming in has embedded NULS.
132 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
134 if ((p = memchr(bp, '\n', n)) != NULL)
136 if ((n = read(sock, bp, n)) == -1)
152 int SockPeek(int sock)
153 /* peek at the next socket character without actually reading it */
158 if ((n = recv(sock, &ch, 1, MSG_PEEK)) == -1)
166 * Use the chargen service to test input beuffering directly.
167 * You may have to uncomment the `chargen' service description in your
168 * inetd.conf (and then SIGHUP inetd) for this to work.
172 int sock = SockOpen("localhost", 19);
175 while (SockRead(sock, buf, sizeof(buf)-1))
176 SockWrite(1, buf, strlen(buf));
180 /* socket.c ends here */