P rogramming/C Language

시스템 IP 얻어오기

민트앤라떼 2011. 6. 16. 17:32


#include <iostream.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <arpa/inet.h>

#define ER_SOCKET       -101
#define ER_ADDR         -102


int get_if_ip(char *inf, u32_int *ip)
{
    int                 s;
    struct ifreq        ifr;
    struct sockaddr_in  *sin = (struct sockaddr_in *)&ifr.ifr_addr;

    if((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        return ER_SOCKET;
    }
    strncpy(ifr.ifr_name, inf, IFNAMSIZ);
    sin->sin_family = AF_INET;
    if(ioctl(s,SIOCGIFADDR,&ifr) < 0)
    {
        close(s);
        return ER_ADDR;
    }
    close(s);
    *ip = ntohl(sin->sin_addr.s_addr);
    return 0;
}


char *Str4Ip(
        u32_int     addr)
{
    struct in_addr  inaddr;
    static char     str[10][20];
    static int      idx = 0;

    idx = (idx+1) % 10;
    inaddr.s_addr = htonl(addr);
    strcpy(str[idx],inet_ntoa(inaddr));
    return(str[idx]);
}


int main()
{
    unsigned int    my_ip=0;

    get_if_ip("eth0",&my_ip);
    printf("System ip = %d\n",Srt4Ip(my_ip));
}


결과 : 192.168.1.133