[英]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. 我在Ubuntu 12上编写了这个简单的客户端。它是简单的C / C ++连接服务器代码。 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'.
每次我连接到其他主机时,它实际上都连接到“ localhost”。 I am thinking it might be the way my /etc/hosts file is configured but I don't know.
我认为这可能是配置/ etc / hosts文件的方式,但我不知道。
#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 在此行:m_addr.sin_addr.s_addr
I get zero. 我得到零。
You should first resolve the IP address of your Domain name from DNS server then try to establish the connection . 您应该首先从DNS服务器解析域名的IP地址,然后尝试建立连接。
gethostbyname
will give the list of IP address which resolved from the Domain name with the hostent
structure . gethostbyname
会给它从与该域名解析的IP地址列表中hostent
结构。 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 : 然后移到hostent给您的地址列表并测试连接,这是
hostent
结构和gethostbyname
定义:
#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 */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.