我在Ubuntu 12上编写了这个简单的客户端,它是简单的C/C++连接到服务器代码。它可以连接到本地主机。但我不能让它连接到外部服务器。每次我连接到不同的主机时,它实际上连接到'localhost‘。我想这可能是我的/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 //在这一行: m_addr.sin_addr.s_addr
我得零分。
发布于 2013-01-21 14:46:10
您应该首先从DNS服务器解析您的域名的IP地址,然后尝试建立连接。gethostbyname将提供从具有hostent结构的域名解析而来的IP地址列表。您可以使用它,如下所示:
struct hostent *hent;
hent = gethostbyname(host.c_str());然后移动到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 */
}https://stackoverflow.com/questions/14433271
复制相似问题