본문 바로가기

Programming/C & C++

get IP Address

//============================================================
//getIPAddress.c
//============================================================
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#include <net/if.h>

int main (int argc, char *argv[])
{
    struct hostent *he;
    struct sockaddr_in sin;
    char machine_name[ 300 ];

    if (gethostname (machine_name, sizeof (machine_name)))
    {
        perror ("gethostname");
        return -1;
    }


    again:

    he = gethostbyname (machine_name);
    if (he == NULL)
    {
        if (errno == TRY_AGAIN)
        goto again;

        perror ("gethostbyname");
        return -1;
    }

    bzero (&sin, sizeof (struct sockaddr_in));
    sin.sin_family = AF_INET;
    sin.sin_port = htons (80);
    bcopy (he->h_addr_list[ 0 ], &sin.sin_addr, he->h_length);

    printf ("%s\n", inet_ntoa (sin.sin_addr));

    return 0;
}

//============================================================
//getIPAddr.c
//============================================================

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <net/if.h>

int main( int argc, char * argv[] )
{
    struct ifconf ifc;
   
    int s = socket( AF_INET, SOCK_DGRAM, 0 );
    int len = 100 * sizeof(struct ifreq);
   
    char buf[ len ];
    ifc.ifc_len = len;
    ifc.ifc_buf = buf;
 
      int e = ioctl(s,SIOCGIFCONF,&ifc);
      char *ptr = buf;
      int tl = ifc.ifc_len;
      char  szIp[16];
      while ( tl > 0 ){
          struct ifreq* ifr = (struct ifreq *)ptr;
          int si;

        if( ifr->ifr_addr.sa_len > sizeof(struct sockaddr) ){
            si = sizeof(ifr->ifr_name) + ifr->ifr_addr.sa_len;
        }
        else{
            si = sizeof(ifr->ifr_name) + sizeof(struct sockaddr);
        }

        tl -= si;
        ptr += si;

        struct ifreq ifr2;
        ifr2 = *ifr;

        e = ioctl(s,SIOCGIFADDR,&ifr2);

        if( e == -1 ){
            continue;
        }
       
        struct sockaddr a = ifr2.ifr_addr;
        struct sockaddr_in* addr = (struct sockaddr_in*) &a;

        unsigned int ai = ntohl( addr->sin_addr.s_addr );

        // 127.0.0.1 주소는 출력하지 않는다.
        //if((int)((ai>>24)&0xFF) == 127 ){
        //    continue;
        //}   
       
        snprintf( szIp,
            sizeof(szIp),
            "%d.%d.%d.%d",
            (ai>>24)&0xFF,
            (ai>>16)&0xFF,
            (ai>> 8)&0xFF,
            (ai    )&0xFF );
       
        printf("[%s]\n", ifr->ifr_name);
        printf("[%s]\n", szIp);
    }

    close(s);
    return 0;
}