#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <poll.h>
#include <pthread.h>
#include <pwd.h>
#include <netdb.h>
#include <fcntl.h>
#include <arpa/inet.h>
int transport_connect_socket(const char* host/*127.0.0.1*/, const char* port/*2228*/) {
int i, flags, sock = -1;
struct addrinfo hints, *res_list, *res;
/* Connect to a server */
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
i = getaddrinfo(host, port, &hints, &res_list);
if (i != 0) {
fprintf(stderr, "Unable to translate the host address (%s).", gai_strerror(i));
return (-1);
}
for (i = 0, res = res_list; res != NULL; res = res->ai_next) {
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sock == -1) {
/* socket was not created, try another resource */
i = errno;
goto errloop;
}
if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
/* network connection failed, try another resource */
i = errno;
close(sock);
sock = -1;
goto errloop;
}
/* make the socket non-blocking */
if (((flags = fcntl(sock, F_GETFL)) == -1) || (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1)) {
fprintf(stderr, "Fcntl failed (%s).", strerror(errno));
close(sock);
return -1;
}
/* we're done, network connection established */
break;
errloop:
fprintf(stdout, "Unable to connect to %s:%s over %s (%s).", host, port,
(res->ai_family == AF_INET6) ? "IPv6" : "IPv4", strerror(i));
continue;
}
freeaddrinfo(res_list);
if (sock == -1) {
fprintf(stderr, "Unable to connect to %s:%s.", host, port);
}
return (sock);
}
[代码片段] 创建TCP套接字
最新推荐文章于 2023-09-15 16:11:42 发布