gpt4 book ai didi

c++ - 无法绑定(bind)到套接字

转载 作者:行者123 更新时间:2023-11-28 02:12:03 24 4
gpt4 key购买 nike

代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
// #include <thread>
#include <arpa/inet.h>
#include <iostream>

using namespace std;

#define PORT 8888
#define BACKLOG 5

int main(int argc, char const *argv[]) {

int status;
struct addrinfo hints,
*res,
*temp;

char ipstr [INET6_ADDRSTRLEN];
int socket_fd;

memset (&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // Allows both IPv4 and IPv6
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // Allows automatic fill-up of IP (allows using localhost)

if ((status = getaddrinfo (NULL , "8000", &hints, &res)) != 0 ) {
cout << "[-] Error: " << gai_strerror (status) << endl;
exit (EXIT_FAILURE);
}

socket_fd = socket (res->ai_family, res->ai_socktype, res->ai_protocol);
if (socket_fd == -1) {
cout << "[-] Error : Socket couldn't be created" << endl;
exit (EXIT_FAILURE);
}

if (bind (socket_fd, res->ai_addr, res->ai_addrlen) == -1 ) {
cout << "[-] Error: Failed to bind to port" << endl;
exit (EXIT_FAILURE);
}

if (connect (socket_fd, res->ai_addr, res->ai_addrlen) == -1) {
cout << "[-] Error: Failed to connect to remote user" << endl;
exit (EXIT_FAILURE);
}

freeaddrinfo (res); // free the linked list returned by getaddrinfo ()
return 0;
}

代码正在返回:
[-] 错误:绑定(bind)端口失败

无论我将 NULL 放在 getaddrinfo () 的第一个参数上(让它监听 localHost)还是提供一些地址,它都无法将端口绑定(bind)到套接字。正如我通过更改端口值尝试的那样,该端口可用。代码有什么问题?

最佳答案

代码很好,所以当第一次执行时,一切都按预期工作。但是,后续执行同一个程序会报

[-] Error: Failed to bind to port

如果你运行 netstat --tcp --numeric | grep 8000 你会看到8000端口的socket处于TIME_WAIT状态:

bash-4.2$ netstat --tcp --numeric | grep 8000
tcp 0 0 127.0.0.1:8000 127.0.0.1:8000 TIME_WAIT

表示连接已关闭,因此它将在操作系统指定的超时时间内终止(默认为四分钟)。超时到期后,程序将无错误地执行(同样只有一次)。

关于c++ - 无法绑定(bind)到套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35292320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com