0

我有一个奇怪的问题:我编写了一个 c++ 程序,它应该连接到启用 ip 的秤。它使用标准的 c++ 套接字。

当我对真实设备(地址 192.168.30.200 端口 23)运行程序时,我得到 errno=ECONNREFUSED(连接被拒绝)。

当我对在 python 中创建的虚拟服务器运行相同的程序时 - 它就像一个魅力(我正在使用“server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)”等。

当我使用命令“echo "FB_INFO" | netcat -w 3 192.168.30.200 23”(相同的地址和端口)从 bash 连接到秤时,秤会回复正确答案。所以它不是拒绝连接。

我什至不知道如何尝试调试问题出在哪里。

这是我的代码:

#define PORT 60000
#define ADDRESS "10.0.10.100"

int scale_port=PORT;                // scale port number
string scale_ip = ADDRESS;      // scale IP address

// connect to scale, and process commands in a loop.
// upon succesfull processing of every complete set of commands
// execute given OS script/shell/command [NOT IMPLEMENTED]
int daemon_connection(int sock, struct sockaddr_in serv_addr)
{
    int valread=0;
    int connectstatus=connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

        if (connectstatus<0)
        //if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
        {
            cout << "DAEMON:Error - socket connection failed status "<< connectstatus;
        cout << " errno=" << errno << endl;
        socketErrPrint(errno);
            return -1;
        }
        cout << "DAEMON: connected to socket" << sock << endl;
        struct timeval timeout;
        timeout.tv_sec = 3;
        timeout.tv_usec = 0;
        setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));

(...)
}

// the main loop: create socket, parse address and call connect to scale
// and retry forever if connection broken or unsuccesfull
int daemon(string addr, int port)
{
    int sock = 0;
        struct sockaddr_in serv_addr;
        if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        {
            cout << "DAEMON: Socket creation error" << endl;
            return -1;
        }

        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(PORT);

        // Convert IPv4 and IPv6 addresses from text to binary form
        if (inet_pton(AF_INET, addr.c_str(), &serv_addr.sin_addr) <= 0)
        {
            cout << "DAEMON: error - invalid address "<< addr << " or address not supported" << endl;
            return -1;
        }
        int result=daemon_connection(sock,serv_addr);
}

(...)
4

0 回答 0