본문 바로가기

UNIX_LINUX_C_C++

IBM AIX 에서 IP 주소 알아내기

출처 : http://blog.daum.net/aswip/8049786

소스 파일 :

#include <stdio.h>
#include <sys/ndd_var.h>
#include <sys/kinfo.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <errno.h>

int main(int argc, char **argv)
{
int sockfd, i = 0, intrface, size = 0, retn = 0;
struct ifreq *buf = NULL;
struct arpreq arp;
struct ifconf ifc;
struct kinfo_ndd *start = 0, *nddp = 0;
void *end;
struct sockaddr_in *sa = NULL;

if ((sockfd = socket (AF_INET, SOCK_DGRAM, 0)) <= 0)
return errno;

if ( ioctl(sockfd, SIOCGSIZIFCONF, &size) == -1 )
{
close(sockfd);
return -1;
}

if ( size <= 0 )
{
close(sockfd);
return -1;
}

size = (size / sizeof(struct ifreq)) + 1;

if ( (buf = (struct ifreq *)malloc(sizeof(struct ifreq) * size)) == NULL )
{
close(sockfd);
return -1;
}

if ((size = getkerninfo(KINFO_NDD, 0, 0, 0)) <= 0)
{
perror("getkerninfo : ");
close(sockfd);
free(buf);
return -1;
}

if ( (nddp = (struct kinfo_ndd *)malloc(size)) == NULL )
{
perror("malloc : ");
close(sockfd);
free(buf);
return -1;
}

/* getting ethernet card info (ex. mac address, name, alias) */
if (getkerninfo(KINFO_NDD, nddp, &size, 0) < 0)
{
perror("getkerninfo : ");
close(sockfd);
free(buf);
return -1;
}

start = nddp;
end = (void *)nddp + size;

ifc.ifc_len = size * sizeof(struct ifreq);
ifc.ifc_buf = (caddr_t) buf;

if (!ioctl (sockfd, SIOCGIFCONF, (char *)&ifc))
{
intrface = ifc.ifc_len / sizeof (struct ifreq);
printf("interface num is intrface=%d\n",intrface);
}

while (intrface-- > 0)
{
if ( ioctl(sockfd, SIOCGIFFLAGS, (char *) &buf[intrface]) == -1 )
continue;

if ( (buf[intrface].ifr_flags & IFF_LOOPBACK ) == IFF_LOOPBACK)
continue;

/* getting ip from ethernet card */
if ( (ioctl(sockfd, SIOCGIFADDR, (char *) &buf[intrface])) == -1 )
continue;

nddp = start;
while (((void *)nddp < end))
{
if ( strcmp(nddp->ndd_alias, buf[intrface].ifr_name) == 0 )
{
sa = (struct sockaddr_in*)(&buf[intrface].ifr_addr);
printf("%s, IP %s, Mac ", buf[intrface].ifr_name, inet_ntoa(sa->sin_addr));

for (i=0; i<6; ++i)
printf("%0X.", (unsigned char)nddp->ndd_addr[i]);

printf("\n");
break;
}
nddp++;
}
}

close(sockfd);
free(buf);
free(nddp);
return 0;
}