当我们的程序是单进程的时候,居如connect、read、accept、gethostbyname之类的网络API
这里我们使用的办法是设置一个时钟,如果gethostbyname在指定的时间内尚未返回,时钟会强制其返回,得到的返回值显然是空指针,等价于告诉用户主机未连如互联网或者该域名无法解析。为了实现这一功能,我们需要重新封装一个形如gethostbyname的函数来获取
#include
#include
static sigjmp_buf jmpbuf;
static void alarm_func()
{
siglongjmp(jmpbuf, 1);
}
static struct hostent *timeGethostbyname(const char *domain, int timeout)
{
struct hostent *ipHostent = NULL;
signal(SIGALRM, alarm_func);
if(sigsetjmp(jmpbuf, 1) != 0)
{
alarm(0);//timout
signal(SIGALRM, SIG_IGN);
return NULL;
}
alarm(timeout);//setting alarm
ipHostent = gethostbyname(domain);
signal(SIGALRM, SIG_IGN);
return ipHostent;
}
int getIPbyDomain(const char* domain, char* ip)
{
struct hostent *answer;
answer = timeGethostbyname(domain, 10);
if (NULL == answer)
{
herror("gethostbyname");//the error function of itself
return -1;
}
if (answer->h_addr_list[0])
inet_ntop(AF_INET, (answer->h_addr_list)[0], ip, 16);
else
return -1;
return 0;
}
这样,如果我们想获得域名”www.cpplive.com” 所指向的IP地址,且要求在3秒内返回结果,则可以调用如下语句实现:
char cppliveIP[32];
char cpplive[32] = {"www.cpplive.com"};
if (getIPbyDomain(cpplive, cppliveIP))
printf("The domain not exist or the network disconnected!\n");
else
printf("The IP of %s is %s\n", cpplive, cppliveIP);
除非注明,文章均为CppLive 编程在线原创,转载请注明出处,谢谢。