6 #include <netinet/in.h>
8 #include <netinet/tcp.h>
13 #include <sys/socket.h>
18 #define LOG_TAG "socket"
31 return open_socket_switch(ip, port,
NONE);
36 return open_socket_switch(ip, port,
NODELAY);
41 return open_socket_switch(ip, port,
REUSEADDR);
47 struct addrinfo hints, *servinfo, *p;
52 snprintf(sport, 6,
"%d", port);
54 memset(&hints, 0,
sizeof hints);
55 hints.ai_family = AF_INET;
56 hints.ai_socktype = SOCK_STREAM;
58 if ((rv = getaddrinfo(ip, sport, &hints, &servinfo)) != 0)
60 LOGW(
"Error in getaddrinfo: %s\n", gai_strerror(rv));
65 for (p = servinfo; p != NULL; p = p->ai_next)
67 if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
69 LOGW(
"Socket connect error: %s", strerror(errno));
74 setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &yes,
sizeof(
int));
76 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(
int));
78 if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
80 LOGW(
"Socket connect error: %s", strerror(errno));
91 LOGW(
"Failed to connect to %s:%d", ip, port);
95 freeaddrinfo(servinfo);
socket_t open_socket(const char *ip, short port)
Connect to a host:port couple.
enum open_type open_type_t
int socket_t
Alias to differenciate between regular ints and socket fds.
socket_t open_socket_nodelay(const char *ip, short port)
Open a socket with TCP_NODELAY.
socket_t open_socket_reuseaddr(const char *ip, short port)
Open a socket with SO_REUSEADDR.
#define LOGW(...)
Log at WARNING level.
#define SOCKET_ERROR
Alias for the recv() return value in case of error.
Define socket utilities to simplify networking.