/*
* G ++-o 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: % dname: % sstatus: % daddress: % s ",
I,
Ipconfig. interfaces [I]. name,
Ipconfig. interfaces [I]. status,
Ipconfig. interfaces [I]. address );
Return 1;
}