user3253375
user3253375

Reputation: 57

Connection Refused when trying to connect to tcp socket (linux)

I'm working on ubunto linux version 14.04 (linux) using VM ware

I've created TCP socket in c++ under ubunto 14.04 (linux) but when i try to use the "connect" method of the socket it fails and says that the connection refused. I Tried to turn off the firewall in my windows (10) computer, but it didn't help at all.

your help would be highly appreciated!

TCPSocket::TCPSocket(string peerIp, int port) {
    // Open TCP socket
    this->connected_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (this->connected_sock < 0) {
        perror("Error opening channel");
    }

    // Set the peer address to connect to
    bzero(&this->peerAddr, sizeof(this->peerAddr));
    this->peerAddr.sin_family = AF_INET;
    this->peerAddr.sin_addr.s_addr = inet_addr(peerIp.c_str());
    this->peerAddr.sin_port = htons(port);

    // FAILED HERE
    if (connect(this->connected_sock, (struct sockaddr *) &this->peerAddr,
            sizeof(this->peerAddr)) < 0) {
        perror("Error establishing communications");
        throw "Error establishing communications";
    }
}

Upvotes: 0

Views: 11547

Answers (2)

user3253375
user3253375

Reputation: 57

So i solved the issue!

I was dumb...

the soultion is in the calling => i called different ports.

server listens to port 13301 and the clients needs to connect to the same port, only then the server accept the client and opens new socket with him..

Thanks so much for you kind help !

Upvotes: 0

Tom Trebicky
Tom Trebicky

Reputation: 648

There is nothing wrong with your code. connection refused means that somewhere along the path somebody sent a TCP reset packet back to the original source. Use a network traffic monitoring tool (e.g. tcpdump, wireshark) at notable points to track down where it's failing. A tcpdump example: tcpdump -i <interface_name> -nnvvvXX host <destination_ip> and tcp port <destination_port>

Upvotes: 1

Related Questions