gpt4 book ai didi

c++ - 为什么在 C++ 中不监听端口

转载 作者:行者123 更新时间:2023-11-27 22:33:06 26 4
gpt4 key购买 nike

我正在尝试使用套接字设置服务器,但我希望被监听的端口似乎无法正常工作。当我运行 netstat -nlp 命令时,端口不会显示。

int openListenFd(int port){
int socketDesc, newSocket;
int opt = 1;
struct sockaddr_in server, client;
string message;
cout << "The port is " << port << endl;
int myPort = 3207;
socketDesc = socket(AF_INET, SOCK_STREAM, 0);
if(socketDesc == -1){
cout << "ERROR CREATING SOCKET DESCRIPTOR" << endl;
exit(EXIT_FAILURE);
}

if(setsockopt(socketDesc, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))){
cout << "Setsocket error" << endl;
exit(EXIT_FAILURE);
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(myPort);

if(bind(socketDesc, (struct sockaddr *)&server, sizeof(server)) < 0){
cout << "BIND FAILED" << endl;
exit(EXIT_FAILURE);
}
cout << "Bind finished" << endl; //Page 982

if(listen(socketDesc,10) < 0){
close(socketDesc);
}

return socketDesc;

}

这应该返回连接的文件描述符,并且在任何时候都不会出错。它稍后到达它只是等待的 accept() 调用,可能是因为端口不工作,没有客户端可以连接到它。

最佳答案

按我的预期工作。测试程序:

#include <string>
#include <iostream>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <unistd.h>

using namespace std;

int openListenFd() {
int socketDesc;
int opt = 1;
struct sockaddr_in server;
string message;
int port = 3207;
cout << "The port is " << port << endl;
socketDesc = socket(AF_INET, SOCK_STREAM, 0);
if(socketDesc == -1){
cout << "ERROR CREATING SOCKET DESCRIPTOR" << endl;
exit(EXIT_FAILURE);
}

if(setsockopt(socketDesc, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))){
cout << "Setsocket error" << endl;
exit(EXIT_FAILURE);
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(port);

if(bind(socketDesc, (struct sockaddr *)&server, sizeof(server)) < 0){
cout << "BIND FAILED" << endl;
exit(EXIT_FAILURE);
}
cout << "Bind finished" << endl; //Page 982

if(listen(socketDesc,10) < 0){
close(socketDesc);
}

return socketDesc;
}

int main() {
int fd = openListenFd();
int rc = system("netstat -tlnp");
return !(fd && !rc);
}

输出:

Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   
tcp 0 0 127.0.0.1:3207 0.0.0.0:* LISTEN 31807/test

关于c++ - 为什么在 C++ 中不监听端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58487981/

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