LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Kernel (https://www.linuxquestions.org/questions/linux-kernel-70/)
-   -   How to get the lowest/smallest local IP? (https://www.linuxquestions.org/questions/linux-kernel-70/how-to-get-the-lowest-smallest-local-ip-760391/)

yaplej 10-07-2009 03:56 PM

How to get the lowest/smallest local IP?
 
Hello,

I need to use the lowest/smallest IP address of the host in my module. Is there an easy way to get a list of the current IP addresses?

Thanks.

yaplej 10-08-2009 11:37 AM

Found some code that supposedly does does this, but have not been able to get it to return the correct address.

Code:

/* eth0 to __u32 IP address */
static inline __u32
getlocalIP(void){
        struct net_device *device;
        struct in_device *in_dev;
        struct in_ifaddr *if_addr;
        char dev_name[20];
        __u8 *addr;

        sprintf(dev_name,"eth%d",0);
        device = dev_get_by_name(dev_name);
        in_dev = (struct in_device *)device->ip_ptr;
        if_addr = in_dev->ifa_list;

        addr = (char *)&if_addr->ifa_local;
       
        printk(KERN_ALERT "Eth0 IP: %lu.",
        (unsigned int long)addr);
       
        return (__u32)addr;
}


yaplej 10-08-2009 12:17 PM

Got it working.

Code:

/* eth0 to __u32 IP address */
static inline __u32
getlocalIP(void){
        struct net_device *device;
        struct in_device *in_dev;
        struct in_ifaddr *if_addr;
        char dev_name[20];
        __u32 localIP;
        __u8 *addr;
       
        localIP = 0;

        sprintf(dev_name,"eth%d",0);
        device = dev_get_by_name(dev_name);
        in_dev = (struct in_device *)device->ip_ptr;
        if_addr = in_dev->ifa_list;
       
        addr = (char *)&if_addr->ifa_local;

        localIP += (addr[0] << 24);
        localIP += (addr[1] << 16);
        localIP += (addr[2] << 8);
        localIP += addr[3];

        return localIP;
}



All times are GMT -5. The time now is 03:02 PM.