Note that there are some explanatory texts on larger screens.

plurals
  1. POLinked List in C and getifaddrs()
    text
    copied!<p>I've a problem with linked list. I'm using getifaddrs() to get ifaces info in Linux.</p> <p>At first, i created an struct for save the interfaces infos.</p> <p>This is a struct:</p> <pre><code> typedef struct iface { char * interface_name; char * interface_addr_ipv4; char * interface_addr_ipv6; char * interface_netmask; char * interface_broadcast; char * interface_mac_addr; int interface_active; struct iface * next_interface; } Interface; </code></pre> <p>After this, i identify all ifaces of system in this way, even if they are not configured with an IP:</p> <pre><code> if (getifaddrs(&amp;ifaddr) == -1) return GET_INFO_IFACES_FAILED; struct iface * iface_aux; struct ifaddrs * ifaddr_aux; struct sockaddr_in * ip; iface_aux = iface; for (ifaddr_aux=ifaddr;ifaddr_aux!=NULL;ifaddr_aux=ifaddr_aux-&gt;ifa_next) { iface_aux-&gt;interface_name = ifaddr_aux-&gt;ifa_name; if (ip-&gt;sin_family == AF_PACKET) { get_interface_mac_addr(iface_aux); iface_aux-&gt;interface_addr_ipv4 = NULL; iface_aux-&gt;interface_addr_ipv6 = NULL; iface_aux-&gt;next_interface = (Interface *) malloc(sizeof (Interface)); iface_aux = iface_aux-&gt;next_interface; iface_aux-&gt;next_interface = NULL; } } </code></pre> <p>After all this, i do other loop to get ip address of interfaces, this is the code:</p> <pre><code>iface_aux = iface; //go to the firts pointer for (ifaddr_aux=ifaddr;ifaddr_aux!=NULL;ifaddr_aux=ifaddr_aux-&gt;ifa_next) { ip = (struct sockaddr_in *) ifaddr_aux-&gt;ifa_addr; if (ip-&gt;sin_family == AF_INET) { get_interface_ifaddr(iface_aux, ip); get_interface_netmask(iface_aux, ifaddr); get_interface_broadcast(iface_aux, ifaddr); iface_aux = iface_aux-&gt;next_interface; } } </code></pre> <p>The code of function get_interface_ifaddr is:</p> <pre><code>int get_interface_ifaddr(Interface * iface, struct sockaddr_in * ip) { iface-&gt;interface_addr_ipv4 = inet_ntoa(ip-&gt;sin_addr); if (iface-&gt;interface_addr_ipv4 == NULL) return GET_IFADDR_FAILED; return GET_IPADDR_SUCCESS; } </code></pre> <p>The problem is, when i do another loop to see the interfaces infos, all nodes of the list, stay with the last ip:</p> <pre><code>for (iface_aux=iface;iface_aux-&gt;next_interface!=NULL;iface_aux=iface_aux-&gt;next_interface) { printf("Interface Name: %s\n", iface_aux-&gt;interface_name); printf("Interface IP: %s\n", iface_aux-&gt;interface_addr_ipv4); } </code></pre> <p>The strange thing is that the name of the interfaces is correct, but when i get the address, all nodes of the list, are to the same address.</p> <p>Someone know what is going on?</p> <p>PS: i'm new in c and linked list.</p> <p>Thanks for your atention.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload