论坛交流
首页办公自动化| 网页制作| 平面设计| 动画制作| 数据库开发| 程序设计| 全部视频教程
应用视频: Windows | Word2007 | Excel2007 | PowerPoint2007 | Dreamweaver 8 | Fireworks 8 | Flash 8 | Photoshop cs | CorelDraw 12
编程视频: C语言视频教程 | HTML | Div+Css布局 | Javascript | Access数据库 | Asp | Sql Server数据库Asp.net  | Flash AS
当前位置 > 文字教程 > C语言程序设计教程
Tag:新手,函数,指针,数据类型,对象,Turbo,入门,运算符,数组,结构,二级,,tc,游戏,试题,问答,编译,视频教程

用C语言得到Linux本机的IP地址

文章类别:C语言程序设计 | 发表日期:2008-9-24 14:44:58

#include <stdio.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>
#include <net/if_arp.h>

#define MAXINTERFACES 16

main (argc, argv)
register int argc;
register char *argv[];
{
register int fd, intrface, retn = 0;
struct ifreq buf[MAXINTERFACES];
struct arpreq arp;
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);
printf("interface num is intrface=%d\n\n\n",intrface);
while (intrface-- > 0)
{
printf ("net device %s\n", buf[intrface].ifr_name);

/*Jugde whether the net card status is promisc*/
if (!(ioctl (fd, SIOCGIFFLAGS, (char *) &buf[intrface]))) {
if (buf[intrface].ifr_flags & IFF_PROMISC) {
puts ("the interface is PROMISC");
retn++;
}
} else {
char str[256];

sprintf (str, "cpm: ioctl device %s", buf[intrface].ifr_name);
perror (str);
}

/*Jugde whether the net card status is up*/
if (buf[intrface].ifr_flags & IFF_UP) {
puts("the interface status is UP");
}
else {
puts("the interface status is DOWN");
}

/*Get IP of the net card */
if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface])))
{
puts ("IP address is:");
puts(inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));
puts("");
//puts (buf[intrface].ifr_addr.sa_data);
}
else {
char str[256];

sprintf (str, "cpm: ioctl device %s", buf[intrface].ifr_name);
perror (str);
}

/*Get HW ADDRESS of the net card */
if (!(ioctl (fd, SIOCGIFHWADDR, (char *) &buf[intrface])))
{
puts ("HW address is:");

printf("%02x:%02x:%02x:%02x:%02x:%02x\n",
(unsigned char)buf[intrface].ifr_hwaddr.sa_data[0],
(unsigned char)buf[intrface].ifr_hwaddr.sa_data[1],
(unsigned char)buf[intrface].ifr_hwaddr.sa_data[2],
(unsigned char)buf[intrface].ifr_hwaddr.sa_data[3],
(unsigned char)buf[intrface].ifr_hwaddr.sa_data[4],
(unsigned char)buf[intrface].ifr_hwaddr.sa_data[5]);

puts("");
puts("");
}

else {
char str[256];

sprintf (str, "cpm: ioctl device %s", buf[intrface].ifr_name);
perror (str);
}
}
} else
perror ("cpm: ioctl");

} else
perror ("cpm: socket");

close (fd);
return retn;
}

全文出自 : chinaunix.net


视频教程列表
文章教程搜索
 
C语言程序设计推荐教程
C语言程序设计热门教程
看全部视频教程
购买方式/价格
购买视频教程: 咨询客服
tel:15972130058