tcp_connect.c 2.26 KB
Newer Older
Jeroen Vreeken's avatar
Jeroen Vreeken committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
	tcp_connect.c
	
	Copyright Jeroen Vreeken (pe1rxq@amsat.org), 2007, 2008, 2011
	Copyright Stichting C.A. Muller Radioastronomiestation, 2007, 2008, 2011

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

 */

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/socket.h>

#include "tcp_connect.h"

int tcp_connect(char *host, int port)
{
	struct addrinfo *result;
	struct addrinfo *entry;
	struct addrinfo hints = { 0 };
	int error;
	int sock = -1;
	char port_str[10];
41
	int tcp_connect_timeout = 1;
Jeroen Vreeken's avatar
Jeroen Vreeken committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
	
	sprintf(port_str, "%d", port);

	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	
	error = getaddrinfo(host, port_str, &hints, &result);
	if (error) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error));
		return -1;
	}
	
	for (entry = result; entry; entry = entry->ai_next) {
		sock = socket(entry->ai_family, entry->ai_socktype,
		    entry->ai_protocol);
		ioctl(sock, FIONBIO, &(int){1});
		if (sock >= 0) {
			fd_set fdset_tx, fdset_err;
			struct timeval tv;
			
			FD_ZERO(&fdset_tx);
			FD_ZERO(&fdset_err);
			
			FD_SET(sock, &fdset_tx);
			FD_SET(sock, &fdset_err);
			
			tv.tv_sec = tcp_connect_timeout;
			tv.tv_usec = 0;
			
			if (connect(sock, entry->ai_addr, entry->ai_addrlen)) {
				while (
				    select(sock+1, NULL, &fdset_tx, &fdset_err, &tv)<0
				    &&
				    (errno == EAGAIN || errno == EINTR));
			
				if (connect(sock, entry->ai_addr, entry->ai_addrlen)) {
					close(sock);
					sock = -1;
				}
			}

			if (sock >= 0) {
				ioctl(sock, FIONBIO, &(int){0});
				break;
			}
		}
	}
	freeaddrinfo(result);
	
Jeroen Vreeken's avatar
Jeroen Vreeken committed
91
92
//	if (sock < 0)
//		printf("Failed to connect\n");
Jeroen Vreeken's avatar
Jeroen Vreeken committed
93
94
	return sock;
}