获得主机的IP和主机名

/*
* 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("--------/nnum:%d/nname:%s/nstatus:%d/naddress:%s/n",
            i,
            ipconfig.interfaces[i].name,
            ipconfig.interfaces[i].status,
            ipconfig.interfaces[i].address);
    return 1;
}

你可能感兴趣的:(socket,struct,UP)