출처 : 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;
}
'UNIX_LINUX_C_C++' 카테고리의 다른 글
[window] 가우시안 분포 랜덤 생성 함수/알고리즘 (0) | 2012.02.02 |
---|---|
[TMAX] 비요청 메세지를 보내기 (0) | 2012.01.17 |
unix 에서 dir 함수 사용 - 링크 (0) | 2011.12.19 |
유닉스에서 디렉토리 다루기 (0) | 2011.12.19 |
pthread 사용방법 (0) | 2011.11.18 |