获得主机的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 charclass CIfCfg
{
public:
enum IFSTATUS {UNKOWN,PROMISC,UP,RUNNING,DOWN};
struct Sifcfg
{
CHAR name[16];
CHAR address[16];
IFSTATUS status;
};
Sifcfg inte易做图ces[MAXINTERFACES];
INT size;CIfCfg()
{
size=0;
}
};INT getLocalHostAddress(CIfCfg& ifcfg)
{
register int fd, int易做图ce;
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;
}int易做图ce = ifc.ifc_len/sizeof(struct ifreq);
while (int易做图ce-- > 0)
{
if ((ioctl (fd, SIOCGIFFLAGS, (char *) &buf[int易做图ce])) < 0)
{
continue;
}
snprintf(ifcfg.inte易做图ces[ifcfg.size].name,
sizeof(ifcfg.inte易做图ces[ifcfg.size].name),
"%s",buf[int易做图ce].ifr_name);if (buf[int易做图ce].ifr_flags & IFF_PROMISC)
{
ifcfg.inte易做图ces[ifcfg.size].status=CIfCfg::PROMISC;
}
else
{
if (buf[int易做图ce].ifr_flags & IFF_UP)
{
ifcfg.inte易做图ces[ifcfg.size].status=CIfCfg::UP;
}
else
{
if (buf[int易做图ce].ifr_flags & IFF_RUNNING)
{
ifcfg.inte易做图ces[ifcfg.size].status=CIfCfg::RUNNING;
}
}
}if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[int易做图ce])))
{
snprintf(ifcfg.inte易做图ces[ifcfg.size].address,
sizeof(ifcfg.inte易做图ces[ifcfg.size].address),
"%s",
inet_ntoa(((struct sockaddr_in*)(&buf[int易做图ce].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.inte易做图ces[i].name,
ipconfig.inte易做图ces[i].status,
ipconfig.inte易做图ces[i].address);
return 1;
}
补充:软件开发 , C语言 ,