Berlin Brown
Berlin Brown

Reputation: 11734

C/C++ Posix tcp/ip network client, only connecting to localhost

I was writing this simple client on Ubuntu 12. It is simple C/C++ connect to server code. It works connecting to localhost. But I can't get it to connect to an outside server. Everytime I connect to a different host, it actually connects to 'localhost'. I am thinking it might be the way my /etc/hosts file is configured but I don't know.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <errno.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>

int connect(const std::string host, const std::string path) {
    const int port = 80;
    // Setup the msock
    int m_sock;
    sockaddr_in m_addr;
    memset(&m_addr, 0, sizeof(m_addr));
    m_sock = socket(AF_INET, SOCK_STREAM, 0);

    int on = 1;
    if (setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, (const char*) &on, sizeof(on)) == -1) {
        return false;
    }

    // Connect //
    m_addr.sin_family = AF_INET;
    m_addr.sin_port = htons(port);
    int status = inet_pton(AF_INET, host.c_str(), &m_addr.sin_addr);

    cout << "Status After inet_pton: " << status << " # " << m_addr.sin_addr.s_addr << endl;
    if (errno == EAFNOSUPPORT) {
        return false;
    }
    status = ::connect(m_sock, (sockaddr *) &m_addr, sizeof(m_addr));
    if (status == -1) {
        return false;
    }
} // End of the function //

At this line: m_addr.sin_addr.s_addr

I get zero.

Upvotes: 0

Views: 2710

Answers (1)

Amir Naghizadeh
Amir Naghizadeh

Reputation: 383

You should first resolve the IP address of your Domain name from DNS server then try to establish the connection . gethostbyname will give the list of IP address which resolved from the Domain name with the hostent structure . you can use it as follow :

struct hostent *hent;
hent = gethostbyname(host.c_str());

Then move over the list of address hostent give you and test the connection,here is the hostent structure and gethostbyname definition :

#include <netdb.h>
struct hostent *gethostbyname(const char *name);

struct hostent {
  char  *h_name;            /* official name of host */
  char **h_aliases;         /* alias list */
  int    h_addrtype;        /* host address type */
  int    h_length;          /* length of address */
  char **h_addr_list;       /* list of addresses */
}

Upvotes: 1

Related Questions