xref: /netbsd-src/external/bsd/ipf/dist/lib/connecttcp.c (revision 13885a665959c62f13a82b3caedf986eaa17aa31)
1 /*	$NetBSD: connecttcp.c,v 1.2 2012/07/22 14:27:36 darrenr Exp $	*/
2 
3 /*
4  * Copyright (C) 2012 by Darren Reed.
5  *
6  * See the IPFILTER.LICENCE file for details on licencing.
7  *
8  * Id: connecttcp.c,v 1.1.1.2 2012/07/22 13:44:38 darrenr 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
connecttcp(char * server,int port)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