• Uncategorized

About c++ : socket-connect-returns-ECONNREFUSED-but-netcat-connects-happily

Question Detail

I have a strange problem: I have written a c++ programm which is supposed to connect to ip enabled scales. It is using standard c++ sockets.

When I run the programm against real device (address 192.168.30.200 port 23) i am getting errno=ECONNREFUSED (connection refused).

When I run the same program against my dummy server created in python – it is working like a charm (I am using “server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)” etc.

When I connect to the scale from bash with a command “echo “FB_INFO” | netcat -w 3 192.168.30.200 23″ (the same address and port) – the scale replies with correct answer. So it is NOT refusing connections.

I have no clue even how to try to debug where is the problem.

Here is my code:

#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);
}

(...)

Question Answer

No answer for now.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.