나의 플랫폼/C언어

Socket Interface Name으로 IP 주소 가져오기.

GsBOB 2013. 3. 6. 08:52

3g,wifi등 인터넷에 interface Name이 있습니다.

이 name을 이용하여 IP를 가져오는 방법이 있네요.

system 입출력 함수인 ioctl을 이용하여 가져오는 방법입니다.


...

#include <sys/socket.h>

#include <netinet/in.h>

#include <net/if.h>

#include <string.h>


...

char *

getIfToIP(char *ifName)

{

 int fd;

 struct ifreq ifr;


 fd = socket(AF_INET, SOCK_DGRAM, 0);


 /* I want to get an IPv4 IP address */

 ifr.ifr_addr.sa_family = AF_INET;


 /* I want IP address attached to interfaceName */

 strncpy(ifr.ifr_name, ifName, IFNAMSIZ-1);

 ioctl(fd, SIOCGIFADDR, &ifr);

 close(fd);

 return  inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr);

}


위와 같이 헤더 파일 추가해주시고 함수를 이용하시면 됩니다.


그럼 오늘도 즐코딩~