2 * socket.c -- socket library functions
4 * For license terms, see the file COPYING in this directory.
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <netinet/in.h>
13 #include <arpa/inet.h>
15 #if defined(STDC_HEADERS)
18 #if defined(HAVE_UNISTD_H)
21 #if defined(HAVE_STDARG_H)
29 #ifdef INADDR_BROADCAST
30 #define INADDR_NONE INADDR_BROADCAST
32 #define INADDR_NONE -1
40 int SockOpen(char *host, int clientPort)
44 struct sockaddr_in ad;
47 memset(&ad, 0, sizeof(ad));
48 ad.sin_family = AF_INET;
50 inaddr = inet_addr(host);
51 if (inaddr != INADDR_NONE)
52 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
55 hp = gethostbyname(host);
58 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
60 ad.sin_port = htons(clientPort);
62 sock = socket(AF_INET, SOCK_STREAM, 0);
65 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
75 #if defined(HAVE_STDARG_H)
76 int SockPrintf(int sock, char* format, ...)
79 int SockPrintf(sock,format,va_alist)
88 #if defined(HAVE_STDARG_H)
89 va_start(ap, format) ;
93 vsprintf(buf, format, ap);
95 return SockWrite(sock, buf, strlen(buf));
99 int SockWrite(int sock, char *buf, int len)
105 n = write(sock, buf, len);
115 int SockRead(int sock, char *buf, int len)
117 char *newline, *bp = buf;
124 * The reason for these gymnastics is that we want two things:
125 * (1) to read \n-terminated lines,
126 * (2) to return the true length of data read, even if the
127 * data coming in has embedded NULS.
129 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
131 if ((newline = memchr(bp, '\n', n)) != NULL)
132 n = newline - bp + 1;
133 if ((n = read(sock, bp, n)) == -1)
143 int SockPeek(int sock)
144 /* peek at the next socket character without actually reading it */
149 if ((n = recv(sock, &ch, 1, MSG_PEEK)) == -1)
157 * Use the chargen service to test input beuffering directly.
158 * You may have to uncomment the `chargen' service description in your
159 * inetd.conf (and then SIGHUP inetd) for this to work.
163 int sock = SockOpen("localhost", 19);
166 while (SockRead(sock, buf, sizeof(buf)-1))
167 SockWrite(1, buf, strlen(buf));
171 /* socket.c ends here */