背景:上层传过来的ip是域名,当用inet_addr()函数进行转换赋值时出现错误,导致Tcp连接失败。
方法:首先判断传过来的ip是否是真的ip还是域名,如果是ip就直接inet_addr(),如果是域名,那就将域名转换成ip,再接着连接。
代码:
struct sockaddr_in addr_server;
memset(&addr_server, 0, sizeof(addr_server));
addr_server.sin_family = AF_INET;
QString strIp(host_ip);
if(!isIP(strIp))
{
HOSTENT *host_entry;
char* toIP = new char[16];
host_entry=gethostbyname(host_ip);
if(host_entry!=0)
{
sprintf(toIP,"%d.%d.%d.%d",
(host_entry->h_addr_list[0][0]&0xff),
(host_entry->h_addr_list[0][1]&0xff),
(host_entry->h_addr_list[0][2]&0xff),
(host_entry->h_addr_list[0][3]&0xff));
}
addr_server.sin_addr.S_un.S_addr = inet_addr(toIP);
}
else
{
addr_server.sin_addr.S_un.S_addr = inet_addr(host_ip);
}
int sum = atoi(host_port);
addr_server.sin_port = htons(sum);
connect(m_socket, (struct sockaddr*)&addr_server,sizeof(addr_server));
static bool isIP(QString IP)
{
QRegExp RegExp("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
return RegExp.exactMatch(IP);
}