Re: Obtaining the ip address of an interface dynamically

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Glynn Clements wrote:

>Glover George wrote:
>  
>
>>Hi, I'm working on a little module here and was wondering what the BEST
>>way to get an interface's current ip address by using it's name (i.e.,
>>eth0) is.  I was trying one way using sockets and it just doesn't seem
>>to reliably give it to me every time.  I was using these two functions
>>below, but I it would return NULL some of the time from
>>IPCon_GetIpAddrByStr sometimes, so I'm not sure.  I need a way to be
>>able to reliably obtain this ip at any give time (due to dhcp, etc). Any
>>pointers?  TIA.
>>
>>struct in_addr * IPCon::IPCon_GetIpAddr(void)
>>{
>>        struct ifreq ifr;
>>        struct sockaddr_in *saddr;
>>        int fd;
>>        fd = get_sockfd();
>>        if (fd >= 0 )
>>        {
>>                strcpy(ifr.ifr_name, m_ifname);
>>                ifr.ifr_addr.sa_family = AF_INET;
>>                if (ioctl(fd, SIOCGIFADDR, &ifr) == 0)
>>                {
>>                        saddr = (sockaddr_in *)&ifr.ifr_addr;
>>                        return &saddr->sin_addr;
>>    
>>
>
>You are returning a pointer to data which is on the stack, and which
>ceases to be valid once you've returned from the function.
>
>You should either have the caller supply the buffer, e.g.
>
>	bool IPCon::IPCon_GetIpAddr(struct in_addr *result)
>
>or allocate the memory dynamically, with malloc() or new.
>

Is it possible to get this information but for an IPv6 address (the 
question I asked a few days ago)?

-- FiX

-
: send the line "unsubscribe linux-net" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html


[Index of Archives]     [Netdev]     [Ethernet Bridging]     [Linux 802.1Q VLAN]     [Linux Wireless]     [Kernel Newbies]     [Security]     [Linux for Hams]     [Netfilter]     [Git]     [Bugtraq]     [Yosemite News and Information]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux PCI]     [Linux Admin]     [Samba]

  Powered by Linux