2 * socket.c -- socket library functions
4 * For license terms, see the file COPYING in this directory.
12 #endif /* HAVE_MEMORY_H */
13 #include <sys/types.h>
14 #include <sys/socket.h>
15 #include <netinet/in.h>
16 #include <arpa/inet.h>
18 #if defined(STDC_HEADERS)
21 #if defined(HAVE_UNISTD_H)
24 #if defined(HAVE_STDARG_H)
33 #ifdef INADDR_BROADCAST
34 #define INADDR_NONE INADDR_BROADCAST
36 #define INADDR_NONE -1
39 #endif /* INET_ATON */
41 int SockOpen(const char *host, int clientPort)
46 #endif /* INET_ATON */
47 struct sockaddr_in ad;
50 memset(&ad, 0, sizeof(ad));
51 ad.sin_family = AF_INET;
53 /* we'll accept a quad address */
55 inaddr = inet_addr(host);
56 if (inaddr != INADDR_NONE)
57 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
60 if (!inet_aton(host, &ad.sin_addr))
61 #endif /* INET_ATON */
63 hp = gethostbyname(host);
66 * Add a check to make sure the address has a valid IPv4 or IPv6
67 * length. This prevents buffer spamming by a broken DNS.
69 if (hp == NULL || (hp->h_length != 4 && hp->h_length != 8))
72 memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
74 ad.sin_port = htons(clientPort);
76 sock = socket(AF_INET, SOCK_STREAM, 0);
79 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
89 #if defined(HAVE_STDARG_H)
90 int SockPrintf(int sock, char* format, ...)
93 int SockPrintf(sock,format,va_alist)
102 #if defined(HAVE_STDARG_H)
103 va_start(ap, format) ;
107 #ifdef HAVE_VSNPRINTF
108 vsnprintf(buf, sizeof(buf), format, ap);
110 vsprintf(buf, format, ap);
113 return SockWrite(sock, buf, strlen(buf));
117 int SockWrite(int sock, char *buf, int len)
123 n = write(sock, buf, len);
133 int SockRead(int sock, char *buf, int len)
135 char *newline, *bp = buf;
142 * The reason for these gymnastics is that we want two things:
143 * (1) to read \n-terminated lines,
144 * (2) to return the true length of data read, even if the
145 * data coming in has embedded NULS.
147 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
149 if ((newline = memchr(bp, '\n', n)) != NULL)
150 n = newline - bp + 1;
151 if ((n = read(sock, bp, n)) == -1)
161 int SockPeek(int sock)
162 /* peek at the next socket character without actually reading it */
167 if ((n = recv(sock, &ch, 1, MSG_PEEK)) == -1)
175 * Use the chargen service to test input beuffering directly.
176 * You may have to uncomment the `chargen' service description in your
177 * inetd.conf (and then SIGHUP inetd) for this to work.
181 int sock = SockOpen("localhost", 19);
184 while (SockRead(sock, buf, sizeof(buf)-1))
185 SockWrite(1, buf, strlen(buf));
189 /* socket.c ends here */