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) ;
94 vsnprintf(buf, sizeof(buf), format, ap);
96 vsprintf(buf, format, ap);
99 return SockWrite(sock, buf, strlen(buf));
103 int SockWrite(int sock, char *buf, int len)
109 n = write(sock, buf, len);
119 int SockRead(int sock, char *buf, int len)
121 char *newline, *bp = buf;
128 * The reason for these gymnastics is that we want two things:
129 * (1) to read \n-terminated lines,
130 * (2) to return the true length of data read, even if the
131 * data coming in has embedded NULS.
133 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
135 if ((newline = memchr(bp, '\n', n)) != NULL)
136 n = newline - bp + 1;
137 if ((n = read(sock, bp, n)) == -1)
147 int SockPeek(int sock)
148 /* peek at the next socket character without actually reading it */
153 if ((n = recv(sock, &ch, 1, MSG_PEEK)) == -1)
161 * Use the chargen service to test input beuffering directly.
162 * You may have to uncomment the `chargen' service description in your
163 * inetd.conf (and then SIGHUP inetd) for this to work.
167 int sock = SockOpen("localhost", 19);
170 while (SockRead(sock, buf, sizeof(buf)-1))
171 SockWrite(1, buf, strlen(buf));
175 /* socket.c ends here */