2 * Copyright (c) 2000, Red Hat, Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * A copy of the GNU General Public License can be found at
12 * Written by DJ Delorie <dj@cygnus.com>
16 /* Simplified socket access functions */
29 SimpleSocket::SimpleSocket (char *hostname, int port)
31 static int initted = 0;
36 WSAStartup (MAKEWORD (1,1), &d);
40 buf = (char *) malloc (SSBUFSZ + 3);
46 if (sscanf (hostname, "%d.%d.%d.%d", &i1, &i2, &i3, &i4) == 4)
56 he = gethostbyname (hostname);
59 msg ("Can't resolve `%s'\n", hostname);
62 memcpy (ip, he->h_addr_list[0], 4);
65 s = socket (AF_INET, SOCK_STREAM, 0);
66 if (s == INVALID_SOCKET)
68 msg ("Can't create socket, %d", WSAGetLastError ());
72 struct sockaddr_in name;
74 memset (&name, 0, sizeof (name));
75 name.sin_family = AF_INET;
76 name.sin_port = htons (port);
77 memcpy (&name.sin_addr, ip, 4);
79 if (connect (s, (sockaddr *)&name, sizeof(name)))
81 msg ("Can't connect to %s:%d", hostname, port);
90 SimpleSocket::~SimpleSocket ()
92 if (s != INVALID_SOCKET)
103 if (s == INVALID_SOCKET)
109 SimpleSocket::printf (char *fmt, ...)
111 char localbuf[SSBUFSZ];
113 va_start (args, fmt);
114 vsprintf (localbuf, fmt, args);
115 return send (s, localbuf, strlen (localbuf), 0);
119 SimpleSocket::write (char *localbuf, int len)
121 return send (s, localbuf, len, 0);
125 SimpleSocket::fill ()
130 int n = SSBUFSZ - putp;
133 int r = recv (s, buf + putp, n, 0);
143 SimpleSocket::gets ()
145 if (getp > 0 && putp > getp)
147 memmove (buf, buf+getp, putp-getp);
154 // getp is zero, always, here, and putp is the count
156 while ((nl = (char *)memchr (buf, '\n', putp)) == NULL && putp < SSBUFSZ)
163 while ((*nl == '\n' || *nl == '\r') && nl >= buf)
176 #define MIN(a,b) ((a) < (b) ? (a) : (b))
179 SimpleSocket::read (char *ubuf, int ulen)
184 n = MIN (ulen, putp-getp);
185 memmove (ubuf, buf+getp, n);
193 n = recv (s, ubuf, ulen, 0);