2 * Socket functions for ctdlsalearn
4 * This is open source software for the Linux operating system, licensed under GPL v3
12 #include <sys/types.h>
14 #include <sys/socket.h>
22 #define INADDR_NONE 0xffffffff
27 int uds_connectsock(char *sockpath)
29 struct sockaddr_un addr;
32 memset(&addr, 0, sizeof(addr));
33 addr.sun_family = AF_UNIX;
34 strncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
36 s = socket(AF_UNIX, SOCK_STREAM, 0);
38 if (verbose) fprintf(stderr, "Can't create socket[%s]: %s\n", sockpath, strerror(errno));
42 if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
43 if (verbose) fprintf(stderr, "Can't connect [%s]: %s\n", sockpath, strerror(errno));
53 * sock_read_to() - input binary data from socket, with a settable timeout.
54 * Returns the number of bytes read, or -1 for error.
55 * If keep_reading_until_full is nonzero, we keep reading until we get the number of requested bytes
57 int sock_read_to(int sock, char *buf, int bytes, int timeout, int keep_reading_until_full)
71 retval = select(sock+1, &rfds, NULL, NULL, &tv);
73 if (FD_ISSET(sock, &rfds) == 0) { /* timed out */
74 if (verbose) fprintf(stderr, "sock_read() timed out.\n");
78 rlen = read(sock, &buf[len], bytes-len);
80 if (verbose) fprintf(stderr, "sock_read() failed: %s\n", strerror(errno));
84 if (!keep_reading_until_full) return(len);
91 * sock_read() - input binary data from socket.
92 * Returns the number of bytes read, or -1 for error.
94 int sock_read(int sock, char *buf, int bytes, int keep_reading_until_full)
96 return sock_read_to(sock, buf, bytes, 30, keep_reading_until_full);
101 * sock_write() - send binary to server.
102 * Returns the number of bytes written, or -1 for error.
104 int sock_write(int sock, char *buf, int nbytes)
106 int bytes_written = 0;
108 while (bytes_written < nbytes) {
109 retval = write(sock, &buf[bytes_written],
110 nbytes - bytes_written);
114 bytes_written = bytes_written + retval;
116 return (bytes_written);
122 * Input string from socket - implemented in terms of sock_read()
125 int sock_getln(int sock, char *buf, int bufsize)
129 /* Read one character at a time.
132 if (sock_read(sock, &buf[i], 1, 1) < 0) return(-1);
133 if (buf[i] == '\n' || i == (bufsize-1))
137 /* If we got a long line, discard characters until the newline.
139 if (i == (bufsize-1))
140 while (buf[i] != '\n')
141 if (sock_read(sock, &buf[i], 1, 1) < 0) return(-1);
143 /* Strip any trailing CR and LF characters.
147 && ( (buf[i - 1]==13)
148 || ( buf[i - 1]==10)) ) {
158 * sock_puts() - send line to server - implemented in terms of serv_write()
159 * Returns the number of bytes written, or -1 for error.
161 int sock_puts(int sock, char *buf)
165 i = sock_write(sock, buf, strlen(buf));
167 j = sock_write(sock, "\n", 1);
173 void sock_printf(int sock, const char *format,...)
179 va_start(arg_ptr, format);
180 vsnprintf(buf, sizeof buf, format, arg_ptr);
183 sock_write(sock, buf, strlen(buf));