xxb_xxb
驱动牛犊
驱动牛犊
  • 注册日期2002-10-12
  • 最后登录2002-11-19
  • 粉丝0
  • 关注0
  • 积分0分
  • 威望0点
  • 贡献值0点
  • 好评度0点
  • 原创分0分
  • 专家分0分
阅读:1718回复:3

LINUX下怎么通过主机名查询IP地址?

楼主#
更多 发布于:2002-10-29 16:18
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>


unsigned int GetIPbyName(char *strHostName)
{
struct hostent *pHostent;
struct sockaddr_in addr;
pHostent = gethostbyname(strHostName);
if( pHostent != NULL )
{
printf(\"IP Address : %s\\n\",inet_ntoa(*((struct in_addr *)pHostent->h_addr)));
memcpy(&addr.sin_addr, pHostent->h_addr, pHostent->h_length);
return addr.sin_addr.s_addr;
}
else
return 0;
}

int main()
{
unsigned int nWord;
char strHostName[32];
if (gethostname(strHostName, 32) == -1)
return 1;
nWord  = GetIPbyName(strHostName);
return 0;
}

我这段代码返回本地的IP总是127.0.0.1
各位老大怎么才能返回真实的地址?
xxb_xxb
驱动牛犊
驱动牛犊
  • 注册日期2002-10-12
  • 最后登录2002-11-19
  • 粉丝0
  • 关注0
  • 积分0分
  • 威望0点
  • 贡献值0点
  • 好评度0点
  • 原创分0分
  • 专家分0分
沙发#
发布于:2002-10-29 18:07
没知道的吗?我不相信
minsoft
驱动小牛
驱动小牛
  • 注册日期2001-07-30
  • 最后登录2007-03-06
  • 粉丝0
  • 关注0
  • 积分8分
  • 威望2点
  • 贡献值0点
  • 好评度0点
  • 原创分0分
  • 专家分0分
板凳#
发布于:2002-11-04 09:22
你直接看一下文件/etc/hosts.conf,看看主机与IP地址关系。你就知道为什么了。
再用hosts命令显示一下当前正在使用的主机名称。
少了e,就少了全部
xxb_xxb
驱动牛犊
驱动牛犊
  • 注册日期2002-10-12
  • 最后登录2002-11-19
  • 粉丝0
  • 关注0
  • 积分0分
  • 威望0点
  • 贡献值0点
  • 好评度0点
  • 原创分0分
  • 专家分0分
地板#
发布于:2002-11-04 14:01
to minsoft:
问题已经解决了,gethostbyname只能根据/etc/hosts来给出,所以解决不了问题..
现在我用ioctl函数。

游客

返回顶部