inet_addr 对于 localhost 返回 -1
使用Delphi XE和winsock单元
我有以下代码:
var
fHost: AnsiString;
begin
inet_addr(PAnsiChar(fhost));
fHost
可以是一个IP地址或主机名。
当 fhost = '127.0.0.1'
时,它工作正常,但是,当 fHost = 'localhost'
时,调用失败并返回 -1。我注意到在我的复杂应用程序中,inet_addr
无法解析任何主机名,并且仅适用于 IP 地址。
如果我将此代码取出到一个简单的测试应用程序中,那么解析本地主机(和主机名)就可以正常工作。
我尝试将行 127.0.0.1 localhost
添加到主机文件中,但这没有什么区别。
为什么这个代码在一个应用程序中会失败,而在一个简单的测试工具中却每次都能工作?
Using Delphi XE and the winsock unit
I have the following code:
var
fHost: AnsiString;
begin
inet_addr(PAnsiChar(fhost));
fHost
can be an ip address or a host name.
when fhost = '127.0.0.1'
it works fine however, when fHost = 'localhost'
the call fails and returns -1. I have noticed that in my complex app that inet_addr
fails to resolve any host names and only works with ip addresses.
If I take this code out to a simple test app then resolving localhost (and host names) works fine.
I've tried adding the line 127.0.0.1 localhost
into the hosts file and that made no difference.
Why would this code in one application fail and in a simple test harness work every time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的测试代码可能不正确,
inet_addr
将包含 IP 地址的字符串转换为数值,它不解析主机。为此,请使用gethostbyname
。Your test code is likely incorrect,
inet_addr
converts a string containing an IP address to a numeric value, it does not resolve hosts. Usegethostbyname
for that.