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