程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 獲得主機的IP和主機名

獲得主機的IP和主機名

編輯:關於C語言

/*
* g++ -o gethostip gethostip.cpp
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/param.h>
#include <arpa/inet.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
#define INT int
#define CHAR char

class CIfCfg
{
  public:
    enum IFSTATUS {UNKOWN,PROMISC,UP,RUNNING,DOWN};
    struct Sifcfg
    {
        CHAR name[16];
        CHAR address[16];
        IFSTATUS status;
    };
    Sifcfg interfaces[MAXINTERFACES];
    INT size;

    CIfCfg()
    {
        size=0;
    }
};

INT getLocalHostAddress(CIfCfg& ifcfg)
{
  register int fd, intrface;
  struct ifreq buf[MAXINTERFACES];
  struct ifconf ifc;

  if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) < 0)
  {
          return -1;
  }

  ifc.ifc_len = sizeof(buf);
  ifc.ifc_buf = (caddr_t) buf;
  if (ioctl (fd, SIOCGIFCONF, (char *) &ifc) < 0)
  {
          return -1;
  }

  intrface = ifc.ifc_len/sizeof(struct ifreq);
  while (intrface-- > 0)
  {
        if ((ioctl (fd, SIOCGIFFLAGS, (char *) &buf[intrface])) < 0)
        {
            continue;
        }
        snprintf(ifcfg.interfaces[ifcfg.size].name,
                sizeof(ifcfg.interfaces[ifcfg.size].name),
                "%s",buf[intrface].ifr_name);

        if (buf[intrface].ifr_flags & IFF_PROMISC)
        {
            ifcfg.interfaces[ifcfg.size].status=CIfCfg::PROMISC;
        }
        else
            {
                if (buf[intrface].ifr_flags & IFF_UP)
                {
                    ifcfg.interfaces[ifcfg.size].status=CIfCfg::UP;
                }
                else
                    {
                        if (buf[intrface].ifr_flags & IFF_RUNNING)
                        {
                            ifcfg.interfaces[ifcfg.size].status=CIfCfg::RUNNING;
                        }
                    }
            }

        if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface])))
        {
            snprintf(ifcfg.interfaces[ifcfg.size].address,
                    sizeof(ifcfg.interfaces[ifcfg.size].address),
                    "%s",
                    inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));
        }
        else
            continue;
               
        ifcfg.size++;

    }
    close (fd);
    return ifcfg.size;

}
       
int main(void)
{
    CIfCfg ipconfig;
    int num=getLocalHostAddress(ipconfig);
    for (int i=0; i<num; i++)
        printf("-------- num:%d name:%s status:%d address:%s ",
            i,
            ipconfig.interfaces[i].name,
            ipconfig.interfaces[i].status,
            ipconfig.interfaces[i].address);
    return 1;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved