阅读:1718回复:3
LINUX下怎么通过主机名查询IP地址?
#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 各位老大怎么才能返回真实的地址? |
|
沙发#
发布于:2002-10-29 18:07
没知道的吗?我不相信
|
|
板凳#
发布于:2002-11-04 09:22
你直接看一下文件/etc/hosts.conf,看看主机与IP地址关系。你就知道为什么了。
再用hosts命令显示一下当前正在使用的主机名称。 |
|
|
地板#
发布于:2002-11-04 14:01
to minsoft:
问题已经解决了,gethostbyname只能根据/etc/hosts来给出,所以解决不了问题.. 现在我用ioctl函数。 |
|