xref: /freebsd-src/sbin/ipf/libipf/connecttcp.c (revision 0939cf32c0c180ac0e1974959da6962d16b96c7a)
141edb306SCy Schubert /*
241edb306SCy Schubert  * Copyright (C) 2012 by Darren Reed.
341edb306SCy Schubert  *
441edb306SCy Schubert  * See the IPFILTER.LICENCE file for details on licencing.
541edb306SCy Schubert  *
641edb306SCy Schubert  * $Id: connecttcp.c,v 1.3.2.2 2012/07/22 08:04:24 darren_r Exp $
741edb306SCy Schubert  */
841edb306SCy Schubert 
941edb306SCy Schubert #include "ipf.h"
1041edb306SCy Schubert #include <ctype.h>
1141edb306SCy Schubert 
1241edb306SCy Schubert /*
13*0939cf32SElyes Haouas  * Format expected is one address per line, at the start of each line.
1441edb306SCy Schubert  */
1541edb306SCy Schubert int
connecttcp(char * server,int port)1641edb306SCy Schubert connecttcp(char *server, int port)
1741edb306SCy Schubert {
1841edb306SCy Schubert 	struct sockaddr_in sin;
1941edb306SCy Schubert 	struct hostent *host;
2041edb306SCy Schubert 	int fd;
2141edb306SCy Schubert 
2241edb306SCy Schubert 	memset(&sin, 0, sizeof(sin));
2341edb306SCy Schubert 	sin.sin_family = AF_INET;
2441edb306SCy Schubert 	sin.sin_port = htons(port & 65535);
2541edb306SCy Schubert 
2641edb306SCy Schubert 	if (ISDIGIT(*server)) {
2741edb306SCy Schubert 		if (inet_aton(server, &sin.sin_addr) == -1) {
282582ae57SCy Schubert 			return (-1);
2941edb306SCy Schubert 		}
3041edb306SCy Schubert 	} else {
3141edb306SCy Schubert 		host = gethostbyname(server);
3241edb306SCy Schubert 		if (host == NULL)
332582ae57SCy Schubert 			return (-1);
3441edb306SCy Schubert 		memcpy(&sin.sin_addr, host->h_addr_list[0],
3541edb306SCy Schubert 		       sizeof(sin.sin_addr));
3641edb306SCy Schubert 	}
3741edb306SCy Schubert 
3841edb306SCy Schubert 	fd = socket(AF_INET, SOCK_STREAM, 0);
3941edb306SCy Schubert 	if (fd == -1)
402582ae57SCy Schubert 		return (-1);
4141edb306SCy Schubert 
4241edb306SCy Schubert 	if (connect(fd, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
4341edb306SCy Schubert 		close(fd);
442582ae57SCy Schubert 		return (-1);
4541edb306SCy Schubert 	}
4641edb306SCy Schubert 
472582ae57SCy Schubert 	return (fd);
4841edb306SCy Schubert }
49