如何获得本机ip地址

唐勉的技术博客 2003-07-23 04:20:32
我的程序如下:
int main()
{
char buffer[32];
struct hostent* host;

memset(buffer, 0, 32);
gethostname(buffer, 32);
host=gethostbyname(buffer);
printf("%s!\n", inet_ntoa(*((struct in_addr*)host->addr)));
exit(0);
}

上面的程序打印的结果是127.0.0.1,并不是我本机的ip地址.
请各位高手指教!!!
多谢!!!
...全文
74 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
明白了,谢谢楼上的,马上结贴!!!
oldmaize 2003-07-23
  • 打赏
  • 举报
回复
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
main(int argc, char *argv[])
{
struct sockaddr_in addr;
struct hostent *he;
char **alias;
if(argc <2){
perror("usage: hostname name | ip ...\n");
exit(1);
}
argv ++;
for(; *argv!=NULL; argv ++){
if(inet_aton(*argv, &addr.sin_addr)!=0){
he = gethostbyaddr((char *)&addr.sin_addr, 4, AF_INET);
printf("address information of IP $:\n", *argv);
}else {
he = gethostbyname (*argv);
printf("address information of host %s:\n", *argv);
}
if(he == NULL){
fprintf(stderr, "no address information of %s\n", * argv);
continue;
}
printf("official host name: %s \n", he->h_name);
printf("name aliases:");
for(alias=he->h_aliases; *alias!=NULL ; alias ++)
printf(" %s, ", *alias);
for(alias=he->h_addr_list; *alias!=NULL ; alias ++)
printf(" %s, ", inet_ntoa(*(struct in_addr *)(*alias)));
}
}
fierygnu 2003-07-23
  • 打赏
  • 举报
回复
http://www.chinaunix.net/forum/viewtopic.php?t=85716

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧