Linux 下c编程有什么办法获取本机IP?

AdamsLee 2005-08-30 08:24:35
rt
...全文
2232 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
旭子 2010-06-12
  • 打赏
  • 举报
回复
提供一个可运行的代码,得到的不是回环IP!

#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <net/if.h>
#include <arpa/inet.h>
#define ERRORIP "cannot find host ip"
char *ip_search(void)
{
int sfd, intr;
struct ifreq buf[16];
struct ifconf ifc;
sfd = socket (AF_INET, SOCK_DGRAM, 0);
if (sfd < 0)
return ERRORIP;
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = (caddr_t)buf;
if (ioctl(sfd, SIOCGIFCONF, (char *)&ifc))
return ERRORIP;
intr = ifc.ifc_len / sizeof(struct ifreq);
while (intr-- > 0 && ioctl(sfd, SIOCGIFADDR, (char *)&buf[intr]));
close(sfd);
return inet_ntoa(((struct sockaddr_in*)(&buf[intr].ifr_addr))-> sin_addr);
}
int main(void)
{
printf("%s\n", ip_search());
return 0;
}
jiayouba 2005-08-31
  • 打赏
  • 举报
回复
首先调用gethostname得到本机的名称
再调用gethostbyname,通过主机名得到IP

支持一个
nhew 2005-08-31
  • 打赏
  • 举报
回复
en,楼上正解
  • 打赏
  • 举报
回复
首先调用gethostname得到本机的名称
再调用gethostbyname,通过主机名得到IP
这些都是标准的socket接口
方法与windows差别应该不大
不过我现在没时间试验 :(
yyy790601 2005-08-31
  • 打赏
  • 举报
回复
char *SearchIP()
{
int MAXINTERFACES=16;
char *ip=NULL;
int fd, intrface, retn = 0;
struct ifreq buf[MAXINTERFACES];
struct ifconf ifc;

if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0)
{
ifc.ifc_len = sizeof buf;
ifc.ifc_buf = (caddr_t) buf;
if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc))
{
intrface = ifc.ifc_len / sizeof (struct ifreq);

while (intrface-->0)
{

if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface])))
{
ip=(inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));
break;
}

}
}
close (fd);
return ip;
}
}

头文件记不清了,与网络有关的都加上吧。
sharkhuang 2005-08-31
  • 打赏
  • 举报
回复
gethostbyname
yunzhongjian 2005-08-31
  • 打赏
  • 举报
回复
http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=204211
yyy790601 2005-08-31
  • 打赏
  • 举报
回复
楼上方法得到的ip地址一般是127.0.0.1,回环地址,没什么用的。
yjf7888 2005-08-30
  • 打赏
  • 举报
回复
http://community.csdn.net/Expert/topic/3448/3448838.xml?temp=.9025385

23,120

社区成员

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

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