我试图用C++编写一个演示服务器/客户端程序。我首先在我的Macbook上运行我的服务器程序,打开ngrok,并将因特网上的公共地址转发到我机器上的本地地址。当我试图运行客户端程序连接到服务器时,我看到了一些我不明白的东西:
我为什么看到这些?在理想的情况下,我希望我的服务器接受来自我的客户端程序的连接,而不仅仅是响应HTTP请求。
这是我的代码,如果这有帮助的话:对于客户端,
#include "helpers.hh"
#include <cstdio>
#include <netdb.h>
// usage: -h [host] -p [port]
int main(int argc, char** argv) {
const char* host = "x.xx.xx.xx"; // use the server's ip here.
const char* port = "80";
// parse arguments
int opt;
while ((opt = getopt(argc, argv, "h:p:")) >= 0) {
if (opt == 'h') {
host = optarg;
} else if (opt == 'p') {
port = optarg;
}
}
// look up host and port
struct addrinfo hints, *ais;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // use TCP
hints.ai_flags = AI_NUMERICSERV;
if (strcmp(host, "ngrok") == 0) {
host = "xxxx-xxxx-xxxx-1011-2006-00-27b9.ngrok.io";
}
int r = getaddrinfo(host, port, &hints, &ais);
if (r != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(r));
exit(1);
}
// connect to server
int fd = -1;
for (auto ai = ais; ai && fd < 0; ai = ai->ai_next) {
fd = socket(ai->ai_family, ai->ai_socktype, 0);
if (fd < 0) {
perror("socket");
exit(1);
}
r = connect(fd, ai->ai_addr, ai->ai_addrlen);
if (r < 0) {
close(fd);
fd = -1;
}
}
if (fd < 0) {
perror("connect");
exit(1);
}
freeaddrinfo(ais);
//
printf("Connection established at fd %d\n", fd);
FILE* f = fdopen(fd, "a+");
fwrite("!", 1, 1, f);
fclose(f);
while (true) {
}
}对于服务器:
#include "helpers.hh"
void handle_connection(int cfd, std::string remote) {
(void) remote;
printf("Received incoming connection at cfd: %d\n", cfd);
usleep(1000000);
printf("Exiting\n");
}
int main(int argc, char** argv) {
int port = 6162;
if (argc >= 2) {
port = strtol(argv[1], nullptr, 0);
assert(port > 0 && port <= 65535);
}
// Prepare listening socket
int fd = open_listen_socket(port);
assert(fd >= 0);
fprintf(stderr, "Listening on port %d...\n", port);
while (true) {
struct sockaddr addr;
socklen_t addrlen = sizeof(addr);
// Accept connection on listening socket
int cfd = accept(fd, &addr, &addrlen);
if (cfd < 0) {
perror("accept");
exit(1);
}
// Handle connection
handle_connection(cfd, unparse_sockaddr(&addr, addrlen));
}
}发布于 2021-12-14 05:06:53
与本地路由器中的典型端口转发相反,ngrok不是传输级别(TCP)上的端口转发程序,而是HTTP级别上的请求转发程序。
因此,如果客户端进行TCP连接到外部ngrok服务器,则不会转发任何内容。只有在客户端发送HTTP请求之后,才会确定目标,然后将此请求发送到内部机器上的ngrok连接器,然后由ngrok连接器启动到内部服务器的连接并转发请求。
https://stackoverflow.com/questions/70343892
复制相似问题