connecttcp.c revision 1.1 1 /* $NetBSD: connecttcp.c,v 1.1 2012/03/23 21:20:08 christos Exp $ */
2
3 /*
4 * Copyright (C) 2009 by Darren Reed.
5 *
6 * See the IPFILTER.LICENCE file for details on licencing.
7 *
8 * Id: connecttcp.c,v 1.3.2.1 2012/01/26 05:44:26 darren_r Exp
9 */
10
11 #include "ipf.h"
12 #include <ctype.h>
13
14 /*
15 * Format expected is one addres per line, at the start of each line.
16 */
17 int
18 connecttcp(char *server, int port)
19 {
20 struct sockaddr_in sin;
21 struct hostent *host;
22 int fd;
23
24 memset(&sin, 0, sizeof(sin));
25 sin.sin_family = AF_INET;
26 sin.sin_port = htons(port & 65535);
27
28 if (ISDIGIT(*server)) {
29 if (inet_aton(server, &sin.sin_addr) == -1) {
30 return -1;
31 }
32 } else {
33 host = gethostbyname(server);
34 if (host == NULL)
35 return -1;
36 memcpy(&sin.sin_addr, host->h_addr_list[0],
37 sizeof(sin.sin_addr));
38 }
39
40 fd = socket(AF_INET, SOCK_STREAM, 0);
41 if (fd == -1)
42 return -1;
43
44 if (connect(fd, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
45 close(fd);
46 return -1;
47 }
48
49 return fd;
50 }
51