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