基于 UNIX 套接字的客户端程序中的 C++ connect() 不建立与服务器的连接

标签 c++ linux sockets berkeley-sockets

我在 CentOS 7.0 中使用著名的 Berkeley 套接字接口(interface)用 C++ 编写了一个简单的套接字服务器。我在任何端口上运行它,它等待连接。

然后我运行同样用 C++ 编写的简单客户端程序并将请求发送到 192.168.122.1(这个IP是通过执行命令ip addr找到的)但是拒绝连接。由于担心防火墙,我停止了 httpd.service (APACHE) 并在端口 80 上执行了该过程,但无济于事,我收到错误“连接被拒绝”。

我该怎么办?

** 更新 001 ** 当我运行命令 netstat -l 时,我得到以下输出:

.
.
tcp        0      0 0.0.0.0:9005            0.0.0.0:*               LISTEN
.
.

** 更新 001 结束 ** 以下是输出:

客户端 --> 连接被拒绝

服务器 --> [正在等待...]

代码如下:

客户:

#include <iostream>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>



using namespace std;


namespace TCP {
    class Client {

    public :
        static bool Connect(int argc, char *argv[]) {


            int returnStatus = 0;


            char* buffer[256];


            if (3 != argc) {
                // warn that the port MUST be specified.
                fprintf(stderr, "Incorrect parameter for port and server's address. Usage: %d <port>.\n", argv[0]);
                exit(1); // shut down the application
            }


            // streaming socket is the same as server's one.
            // Note: we use TCP Streaming and not UDP's datagram.
            int socketObject = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);



            //
            struct sockaddr_in serverObject;

            short int portNumber = atoi(argv[1]);

            /**
             * We use memset() of cstring header
             * to set all uninitialized values of
             * the struct serverObject to zero.
             */
            memset(&serverObject,
                   0, sizeof(serverObject));

            // now set the values properly
            serverObject.
                    sin_family = AF_INET;


            serverObject.sin_addr.s_addr = inet_addr(argv[2]);

            serverObject.
                    sin_port = htons(portNumber);


            // we need now to connect to the server by porting out
            // out socketObject
            returnStatus = connect(socketObject, (sockaddr *)&serverObject, sizeof(serverObject));

            if (returnStatus == 0) {
                fprintf(stdout, "Connect successfully done.");
            }
            else {
                fprintf(stderr, "Connection failed! Error %s\n", strerror(errno));
                close(socketObject);

                exit(errno);
            }

            // now it's time to read the data from the server by using read()
            // we read it up to the point of our buffer size
            returnStatus = read(socketObject, buffer, sizeof(buffer));


            if (returnStatus == -1) {
                fprintf(stderr, "cannot read the data.");
                close(socketObject);
                exit(1);
            }
            else if( returnStatus > 0)
            {
                cout << buffer << endl;
                close(socketObject);
            }
        }
    };
}// end of namespaCE

服务器

#include <iostream>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <cstring>
#include <unistd.h>



using namespace std;

const char DATA_BACK_TO_CLIENT[] = "A simple socket server!";

namespace TCP {
    class Server {

    public :
        static bool Connect(int argc, char *argv[]) {

            int returnStatus = 0;

            if (2 != argc) {
                // warn that the port MUST be specified.
                fprintf(stderr, "Incorrect parameter for port. Usage: %d <port>.\n", argv[0]);
                exit(1); // shut down the application
            }

            int socketObject = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

            struct sockaddr_in serverObject;

            int portNumber = atoi(argv[1]);

            /**
     * We use memset() of cstring header
     * to set all uninitialized values of
     * the struct serverObject to zero.
     */
            memset(&serverObject,
                   0, sizeof(serverObject));

            // now set the values properly
            serverObject.
                    sin_family = AF_INET;
            serverObject.sin_addr.
                    s_addr = htonl(INADDR_ANY);
            serverObject.
                    sin_port = htonl(portNumber);


            returnStatus = bind(socketObject, (struct sockaddr *) &serverObject,
                                sizeof(serverObject));

            if (returnStatus != 0) {
                fprintf(stderr, "Cannot do the binding. Socket closed.");
                close(socketObject);
                exit(1);
            }

            returnStatus = listen(socketObject, 5); // 5 is a typical value for backlog
            // which denotes the number of allowed connections in queue, After linux 2.2,
            // only completed connections are counted in the queue.

            if (returnStatus == -1) {
                fprintf(stderr, "Cannot listen on the socketl.");
                close(socketObject);
                exit(1);
            }

            while (1) {
                cout << "Server has started successfully. Info:" << endl;
                cout << "Port Number Listening to: " <<  portNumber << endl;

                int simpleChildSocket = 0;
                struct sockaddr clientSocket = {0};
                int simpleClient = 0;
                socklen_t clientNameLength = sizeof(clientSocket);


                cout << "Listening Status:" << returnStatus << endl;

                /** blocking-state. accept() is a blocking
                 *  function essentially.
                 * **/
                simpleChildSocket = accept(socketObject, &clientSocket,
                                           &clientNameLength);
                cout << "Accept Connection Status: " << simpleChildSocket << endl;
                if (simpleChildSocket == -1) {
                    fprintf(stderr, "Cannot accept connectios.\n");
                    close(socketObject);
                    exit(1);
                }

                /**
         * Handle the incoming request
         * write received data from the server
         */
                write(simpleChildSocket, DATA_BACK_TO_CLIENT, sizeof(DATA_BACK_TO_CLIENT));

                // closing the child socket
                close(simpleChildSocket);
            }

            close(socketObject);
        }
    };
}// end of namespaCE

最佳答案

需要用htons()设置端口号,而不是htonl()。

关于基于 UNIX 套接字的客户端程序中的 C++ connect() 不建立与服务器的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35599740/

相关文章:

c++ - 如何将 C++/Ogre3D 代码链接到 Haskell

python - 在 Python 中传递带空格的命令行参数

c - C 中 shell 命令的历史命令。从哪里开始

linux - 从 IP 地址和端口获取套接字 FD

mysql - Node.js 和 node-mysql - 无法实时广播/发送到站点

c++ - 安装 opencv 时出错,我正在使用 lion 和 xcode4.4

c++ - SFML 不播放任何声音,但没有错误

c++ - 在我的资源类中将通过 loadFromFile() 加载字体的函数更改为 loadFromMemory()

c - 使用 Stat 和 OpenDir()/ReadDir() 在 C 语言中列出当前目录和文件类型(Dir、Reg、Lnk)

php - 同一台PC上的stream_socket_server和stream_socket_client之间的长时间延迟