gethostname返回localhost

375阅读 0评论2011-08-23 sbso_1988
分类:

服务器程序使用了gethostname()函数来获取本机的名称,这个函数在实现上,会先查找/etc/hosts文件的内容,然后查询DNS服务器。如果/etc/hosts文件没有配置,返回的主机名就是localhost,也就是127.0.0.1 。所以,使用bind函数绑定的网络地址其实是一个127.0.0.1 。客户端想connect的话,就找不到连接了

Q:
A program that I need to run will not work. When I try to run it, I get the following error:
*** Cannot identify 'squinnux' IP address. gethostbyname() returns localhost.
My /etc/hosts file is set to:
127.0.0.1 squinnux localhost.localdomain localhost
what can I do to get around this error?
Thanks!

A:
First, squinnex should not be in that line. You should have a seperate line with your actual IP address and host name.
Code:127.0.0.1 localhost.localdomain localhost
192.168.0.1 squinnex
Then /etc/sysconfig/network should have the following lines:
NETWORKING=yes
HOSTNAME=squinnex

直接设置网络地址为INADDR_ANY。有的服务器是多宿主机可能有多个网卡,那么运行在这样的服务器上的服务程序在为其Socket绑定IP地址时可以把htonl(INADDR_ANY)置 给s_addr,这样做的好处是不论哪个网段上的客户程序都能与该服务程序通信;如果只给运行在多宿主机上的服务程序的Socket绑定一个固定的IP地 址,那么就只有与该IP地址处于同一个网段上的客户程序才能与该服务程序通信。
上一篇:g_checksum计算校验值并比较文件内容是否相同
下一篇:grep 详细用法 说明