如何获取本机ip和网卡mac等信息
来源:优易学  2010-1-14 19:27:02   【优易学:中国教育考试门户网】   资料下载   IT书店

  solaris上编译方式是:
  gcc getip.c -DSOLARIS -lsocket -lnsl
  linux直接用
  gcc getip.c
代码如下:
  #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>
  #ifdef SOLARIS
  #include <sys/sockio.h>
  #endif
  #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);
  }

[1] [2] 下一页

责任编辑:cyth

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训