gethostbyname timeout

总结: 下面第一种方法经过测试是可行的,第二种方法(多线程中使用)不能够用信号中断。

so , 对信号的使用要非常小心。



gethostbyname 是阻塞的, 非线程安全的,所以最好使用getaddrinfo , 它是线程安全的。

要给gethostbyname 设置一个超时值, 用信号(alarm)实现是不行的(目前项目嵌入式平台上面测试不行) 。


下面是网上摘录的解决该问题的方法, 对怎么绕过其他系统函数(无论是线程安全还是非安全的)也有很好的借鉴意义


Hello,

I need to add timeout to gethostbyname function in my program. I
googled and searched archives, found some examples with alert(), but
can't make it work :/ I would be grateful of someone could tell me how
to do it.

You can't. Or rather, you shouldn't.

The trick with alarm(2) (not alert()), is to longjmp(3) from the signal
handler to a context created with setjmp(3) before calling gethostbyname(3).
This is, unfortunately, very common in Perl code (in Perl die() actually
uses longjmp() internally to a context set from an eval statement).

However, gethostbyname() keeps internal state, and afterward its unsafe
to call the function again. gethostbyname_r() might be relatively safer,
but you've probably also leaked a file descriptor and memory,
meaning you could only do it so many times from a single process before it
won't work anymore. (And from a strict C perspective, jumping from the
signal handler itself is questionable.)

You do have options.

1) Multiple processes. Use child processes and the
gethostbyname()+alarm() trick, and return the answer down a pipe to
the parent. The child will just kill itself if it timeouts (or
alternatively the parent will set the alarm and kill the child), since it
cannot reliably do it's job afterward.

2) Use threads in conjunction with gethostbyname_r(), or preferably
getaddrinfo(3). Still, you cannot interrupt these functions within the
thread, and so you have a few more decisions to make in terms of how you
handle timeouts.

3) Use a third-party asynchronous DNS library: ADNS, C-Ares and UDNS are
the first ones which comes to mind, the former two probably being the most
popular.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
所有代码在delphi6.0中调试通过。1.GetIP(获取IP地址程序)-GetHostByName(使用GetHostByName函数获取IP程序)-WSAAsyncGetHostByName(使用WSAAsyncGetHostByName函数获取IP地址程序)-MultiIP(多IP情况的处理程序)-ReadIP and IP(关于IP地址和实际的地址的区别)2.GetNetMask(Windows NT&98系统中获取子网掩码)3.获取计算机名(获取或设置本地机和远程计算机名)4.目在线检测(网络连接情况检测)5.DNS的更改和设置(获取DNS设置)6.MAC Addr(网卡信息的获取)7.FTP-API(使用API函数实现FTP客户端程序)8.FTP服务器(FTP服务器程序,实现了FTP服务的大部分功能)9.HTTPGET(使用HTTP协议下载web服务器上的文件或网页)10.WebProxy(实现了Web代理服务器的程序,可以让多个局域网的计算机通过该代理上网)11.Webserver(Web服务器程序,运行该程序可以建立自己的网页服务器)12.telnet(实现了远程登录的客户端功能,使用它可以上BBS)13.TelnetProxy(实现了telnet代理服务器功能的程序)14.mail2000(实现了收发Email的功能,并且能够分析email信件结构,发送附件等)15.netmon(网络流量统计的程序)16.tcplist(网络连接监控的程序)17.tcpipmon(网络配置和统计的使用实例)18.LanFind(局域网资源搜索程序)19.Modem-client(Modem文件传输的客户端程序)20.Modem-server(Modem文件传输的服务器程序)21.RAS-Code(RAS拨号上网程序)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值