0

I was trying to create a TCP server-client chat program in c++ language but in client side connection the connect function isn't working and my connection is getting terminated.I have tried setsockopt method as well as changing the port number but nothing worked.Please do help me!! This is the client side:

#include <iostream>
#include <bits/stdc++.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;

#define IP "10.31.10.157"
int main()
{
    int port=80;
    int buffersize= 1024;
    char buffer[buffersize];
    int client,server;

    sockaddr_in server_addr;
    client=socket(AF_INET,SOCK_STREAM,0);
    if(client<0)
    {
        cout<<"Error creating socket "<<endl;
        exit(1);
    }


    cout<<"Client Socket Created ";
    server_addr.sin_family=AF_INET;
    server_addr.sin_addr.s_addr= inet_addr(IP);
    //server_addr.sin_addr.s_addr= inet_addr(INADDR_ANY);
    server_addr.sin_port=htons(port);
    if(connect(client,(struct sockaddr *) &server_addr, sizeof(server_addr))>0)
    {
        cout<<"\nWrite Bye to end connection\n";

        while(1)
        {
            cout<<"Server: ";
            recv(client,buffer,buffersize,0);
            printf("%s\n",buffer);

            cout<<"Client: ";
            gets(buffer);
            send(client,buffer,buffersize,0);
            if(strcmp(buffer,"Bye")==0)
                break;
        }


    }
    else
        cout<<"Connection Failed";
    cout<<"Connection terminated \n";
    //close(client);
}

server side:

#include <iostream>
#include <bits/stdc++.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;

int main()
{
    int server,client;
    int buffersize=1024;
    char buffer[buffersize];
    int portNum=80;

    struct sockaddr_in server_addr;
    socklen_t size;
    client=socket(AF_INET,SOCK_STREAM,0);
    if(client<0)
    {
        cout<<"Error establishing connection "<<endl;
        return 0;
    }
    cout<<"Socket connection established \n";
    server_addr.sin_family= AF_INET;
    server_addr.sin_addr.s_addr= htons(INADDR_ANY);
    server_addr.sin_port= htons(portNum);
    if(bind(client, (struct sockaddr *) &server_addr, sizeof(server_addr))<0)
    {
        cout<<"Error binding socket "<<endl;
        return 0;
    }
    size= sizeof(server_addr);
    cout<<"Looking for clients";
    listen(client,1);
    server= accept(client, (struct sockaddr *)&server_addr, &size);
    if(server<0)
    {
        cout<<"Error on accepting"<<endl;
        return 0;
    }

    if(server>0)
    {
        cout<<"\nType Bye to end connection\n";
        while(1)
        {
            cout<<"Server: ";
            gets(buffer);
            send(server,buffer,buffersize,0);
            recv(server,buffer,buffersize,0);
            cout<<"Client: ";
            printf("%s",buffer);
            cout<<"\n";
            if(strcmp(buffer,"Bye")==0)
                break;

        }
    }
    cout<<"Connection terminated ";
    //close(client);
}

The server program is working fine but the client isn't connecting to the server!!

Let's Enkindle
  • 138
  • 2
  • 17
  • 1
    Try to isolate the problem and post error-messages or log, don't post a big bunch of code asking for others to fix it, be specific please :) – ymoreau Jan 18 '18 at 10:34
  • 1. Why don't you use `errno` and `strerror` to find out what went wrong? 2. Have you tried a telnet on your server port, did it work? 3. `inet_addr` is deprecated, use [`getaddrinfo`](http://beej.us/guide/bgnet/html/multi/getaddrinfoman.html). 4. Consider using Asio as a more portable networking layer – rustyx Jan 18 '18 at 10:36
  • In what order are you running the client and the server? The client won't connect if there is no server listening. Not saying this is the problem but may be something to look at. – falopsy Jan 18 '18 at 11:30

1 Answers1

0

I'll share my working TCPClient code. See if you can use it (directly or to modify your code);

TCPClient.h

#pragma once
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>


// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")

class TCPClient
{
private:
    static const int DEFAULT_BUFLEN = 512;
    static const std::string DEFAULT_PORT;
    static const int DEFAULT_TIMEOUT = 2000;
    struct addrinfo *result = NULL;
    struct addrinfo *ptr = NULL;
    struct addrinfo hints;
    SOCKET m_connect_socket = INVALID_SOCKET;

public:
    TCPClient();
    ~TCPClient();
    bool Connect(const std::string& address, const std::string& port = DEFAULT_PORT);
    bool Send(const std::string& data);
    bool SetTimeout(int timeout);
    std::string Receive();
};

TCPClient.cpp

#include "stdafx.h"
#include "TCPClient.h"


const std::string TCPClient::DEFAULT_PORT = "50015";

TCPClient::TCPClient()
{   
}

TCPClient::~TCPClient()
{
    closesocket(m_connect_socket);
    WSACleanup();
}



bool TCPClient::Connect(const std::string& address, const std::string& port )
{
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        return false;
    }
    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    if (getaddrinfo(address.c_str(), port.c_str(), &hints, &result) != 0)
    {
        WSACleanup();
        return false;
    }

    for (ptr = result; ptr != NULL; ptr = ptr->ai_next) 
    {
        m_connect_socket = socket(ptr->ai_family, ptr->ai_socktype,
            ptr->ai_protocol);
        if (m_connect_socket == INVALID_SOCKET) 
        {
            WSACleanup();
            return false;
        }

        if (connect(m_connect_socket, ptr->ai_addr, (int)ptr->ai_addrlen) == SOCKET_ERROR) {
            closesocket(m_connect_socket);
            m_connect_socket = INVALID_SOCKET;
            continue;
        }
        if (!SetTimeout(DEFAULT_TIMEOUT))
        {
            return false;
        }
        break;
    }
    freeaddrinfo(result);

    if (m_connect_socket == INVALID_SOCKET) 
    {
        WSACleanup();
        return false;
    }
    return true;
}


bool TCPClient::Send(const std::string& data)
{
    return send(m_connect_socket, data.c_str(), data.length(), 0) != SOCKET_ERROR;
}

bool TCPClient::SetTimeout(int timeout)
{
    return setsockopt(m_connect_socket, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout,
        sizeof(timeout)) == 0;
}

std::string TCPClient::Receive()
{
    char recvbuf[DEFAULT_BUFLEN]="\0";
    recv(m_connect_socket, recvbuf, DEFAULT_BUFLEN, 0);
    return recvbuf;
}

Usage

std::string reply;
std::string message = "message";
TCPClient client;

if (client.Connect("127.0.0.1", "50015"))  //check if connection is successful
{
      client.SetTimeout(1000);  // set the timeout to 1 sec, default timeout=2sec. This line is not necessary
      client.Send(message);      //send message
      reply = client.Receive();   //receive reply
      std::cout << "Reply: " << reply << std::endl;
}
else
{
      std::cout << "Connection to socket un-successful\n";
}

return 0;

Or use boost http://www.boost.org/doc/libs/1_42_0/doc/html/boost_asio/tutorial/tutdaytime1.html.

falopsy
  • 391
  • 4
  • 15