为什么不使用C ++进行端口监听

时间:2019-10-21 14:04:39

标签: c++ networking

我正在尝试使用套接字来设置服务器,但我希望监听的端口似乎无法正常工作。当我运行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()调用,可能是因为端口不起作用,因此没有客户端可以连接到它。

2 个答案:

答案 0 :(得分:2)

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

#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          

答案 1 :(得分:2)

我发现问题确实不是代码。该端口未显示的原因是我正在一台大学Linux服务器上运行它,该服务器上有一台虚拟机。结果,回送地址127.0.0.1无法正常工作。如果我具有管理员权限,则可能可以解决此问题,但事实并非如此。

解决方案是下载ubuntu并在我自己的计算机上运行它,从而使环回地址有效。