linux / unix 에서 자기 IP 얻어오기 ( android 포함 )


linux / unix 에서 자기 IP 얻어오기 ( android 포함 ) ( C, C++ )
( get my ip in android native NDK )
내용 : 로컬의 IP를 찾아 표시한다.
 - 외부 IP를 얻는 방법은 따로...

펌 : http://yegam400.tistory.com/71

보통 자기 ip 알아보는데는 gethostbyname을 많이 사용하지만, 이것은 디바이스의 ethernet(eth0, eth1,...)를 바로 가지고 오므로 정확합니다.
Loop back도 가지고 오네요.
리눅스/유닉스 소스코드입니다.

#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <net/if.h>
#include <arpa/inet.h>
int main()
{
    // 이더넷 데이터 구조체
    struct ifreq *ifr;
    struct sockaddr_in *sin;
    struct sockaddr *sa;
    // 이더넷 설정 구조체
    struct ifconf ifcfg;
    int fd;
    int n;
    int numreqs = 30;
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    // 이더넷 설정정보를 가지고오기 위해서
    // 설정 구조체를 초기화하고
    // ifreq데이터는 ifc_buf에 저장되며,
    // 네트워크 장치가 여러개 있을 수 있으므로 크기를 충분히 잡아주어야 한다.
    // 보통은 루프백주소와 하나의 이더넷카드, 2개의 장치를 가진다.
    memset(&ifcfg, 0, sizeof(ifcfg));
    ifcfg.ifc_buf = NULL;
    ifcfg.ifc_len = sizeof(struct ifreq) * numreqs;
    ifcfg.ifc_buf = malloc(ifcfg.ifc_len);
    for(;;)
    {
/*        ifcfg.ifc_len = sizeof(struct ifreq) * numreqs;
        ifcfg.ifc_buf = realloc(ifcfg.ifc_buf, ifcfg.ifc_len);*/
        if (ioctl(fd, SIOCGIFCONF, (char *)&ifcfg) < 0)
        {
            perror("SIOCGIFCONF ");
            exit;
        }
        break;
    }
    ifr = ifcfg.ifc_req;
    for (n = 0; n < ifcfg.ifc_len; n+= sizeof(struct ifreq))
    {
        sin = (struct sockaddr_in *)&ifr->ifr_addr;
        printf("IP    %s\n", inet_ntoa(sin->sin_addr));
        ifr++;
    }
    close(fd);
    return 0;
}

댓글

이 블로그의 인기 게시물

4,5,6 띠 저항의 색띠를 읽는 법(띠저항 값)

수지에서 인천공항 리무진 버스 (인천공항버스정보)(2022년3월업데이트)

수지에서 김포공항 리무진 버스 ( 2022년 3월 업데이트 )