+static int
+m_streamsocket(const uschar * hostname, struct in_addr * inp, uschar ** errstr)
+{
+ struct hostent * he;
+ int sock;
+
+ /* Lookup the host */
+ if(!(he = gethostbyname(CS hostname))) {
+ *errstr = string_sprintf("failed to lookup host '%s'", hostname);
+ return -1;
+ }
+ *inp = *(struct in_addr *) he->h_addr_list[0];
+
+ /* Create the TCP socket */
+ if ((sock = ip_socket(SOCK_STREAM, AF_INET)) >= 0)
+ return sock;
+
+ *errstr = string_sprintf("unable to acquire socket (%s)", strerror(errno));
+ return -1;
+}
+
+static int
+m_tcpsocket(const uschar * hostname, unsigned int port,
+ struct in_addr * inp, uschar ** errstr)
+{
+ int sock;
+
+ if ((sock = m_streamsocket(hostname, inp, errstr)) < 0)
+ return -1;
+
+ if (ip_connect(sock, AF_INET, (uschar*)inet_ntoa(*inp), port, 5) >= 0)
+ return sock;
+
+ *errstr = string_sprintf("connection to %s, port %u failed (%s)",
+ inet_ntoa(*inp), port, strerror(errno));
+ (void)close(sock);
+ return -1;
+}
+
+static int
+m_tcpsocket_fromdef(const uschar * hostport, uschar ** errstr)
+{
+ int scan;
+ uschar hostname[256];
+ unsigned int port, portlow, porthigh;
+ struct hostent * he;
+ struct in_addr in;
+ int sock;
+
+ /* extract host and port part */
+ scan = sscanf(CS hostport, "%255s %u-%u", hostname, &portlow, &porthigh);
+ if ( scan != 3 ) {
+ if ( scan != 2 ) {
+ *errstr = string_sprintf("invalid socket '%s'", hostport);
+ return -1;
+ }
+ porthigh = portlow;
+ }
+
+ if ((sock = m_streamsocket(hostname, &in, errstr)) < 0)
+ return -1;
+
+ /* Try to connect to all ports low-high until connection is established */
+ for (port = portlow; port <= porthigh; port++)
+ if (ip_connect(sock, AF_INET, (uschar*)inet_ntoa(in), port, 5) >= 0)
+ return sock;
+
+ *errstr = string_sprintf("connection to %s, port %u-%u failed (%s)",
+ inet_ntoa(in), portlow, porthigh, strerror(errno));
+ (void)close(sock);
+ return -1;
+}
+