Chinaunix首页 | 论坛 | 博客
  • 博客访问: 281832
  • 博文数量: 176
  • 博客积分: 2516
  • 博客等级: 少校
  • 技术积分: 1350
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-01 11:18
文章分类
文章存档

2011年(1)

2010年(18)

2009年(157)

我的朋友

分类: LINUX

2010-03-10 09:39:59

在Unix和Linux系统下有两种方法可以获得系统IP地址(gethostbyname和ioctl)

gethostbyname通过域名解析获取对应计算机的网络地址,ioctl是一系列的网络函数获得本机的IP

(推 荐使用ioctl方法,这个方法能给出的ip与ifconfig命令显示的ip一致,并且能不经修改的在arm板上正常运行。而 gethostname()联合gethostbyname()方法给出的ip与ifconfig给出的并不一致,无法使用[还不懂为什么],并且在 arm板上不能正确运行。)

ioctl范例程序
class='codetop'>CODE: class='codemain'>#include
#include
#include
#include
#include
#include
#include
#include


int main(void)
{
int s;
struct ifconf conf;
struct ifreq *ifr;
char buff[BUFSIZ];
int num;
int i;

s = socket(PF_INET, SOCK_DGRAM, 0);
conf.ifc_len = BUFSIZ;
conf.ifc_buf = buff;

ioctl(s, SIOCGIFCONF, &conf);
num = conf.ifc_len / sizeof(struct ifreq);
ifr = conf.ifc_req;

for(i=0;i < num;i++)
{
struct sockaddr_in *sin = (struct sockaddr_in *)(&ifr->ifr_addr);

ioctl(s, SIOCGIFFLAGS, ifr);
if(((ifr->ifr_flags & IFF_LOOPBACK) == 0) && (ifr->ifr_flags & IFF_UP))
{
printf("%s (%s)\n",
ifr->ifr_name,
inet_ntoa(sin->sin_addr));
}
ifr++;
}
}

输出:eth1 (10.60.68.127)
阅读(1004) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~