c - Creating socket compatible with IPv4 and IPv6 -


i writing program can read ip address have been assigned on specific network interface (vlan: eth0.32). won't know if have been assigned ipv4 or ipv6 address try write protocol family agnostic.

the way works is: for, navigate through list of available network interfaces , stop @ point find vlan (eth0.32) read ip address. anyways, @ point of development want works ipv4 leave ready when want implement ipv6 support.

the program works , reads ipv4 address if create socket normally:

sd=socket(pf_inet, sock_dgram, 0); 

but won't able read ipv6 addresses socket family (pf_inet=ipv4) this:

sd=socket(pf_inet6, sock_dgram, 0); setsockopt(sd, sol_socket, ipv6_v6only, 0, sizeof(int)); 

the problem ipv6 socket, fails accomplish if condition read ip address:

if (ioctl(sd, siocgifconf, &ifc) == 0) 

for more information, whole code:

#include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <netdb.h> #include <net/if.h>  int main(int argc, char **argv) {      struct ifconf ifc;     struct ifreq ifr[max_network_interfaces];     int ifc_num, addr, i;     static uint8 sd=0;      sd=socket(pf_inet6, sock_dgram, 0);     setsockopt(sd, sol_socket, ipv6_v6only, 0, sizeof(int)); //i change socket option ipv6_v6only false, should compatible ipv4      if (sd > 0)     {         ifc.ifc_len = sizeof(ifr);         ifc.ifc_ifcu.ifcu_buf = (caddr_t)ifr; //buffer address          if (ioctl(sd, siocgifconf, &ifc) == 0)         {             ifc_num = ifc.ifc_len / sizeof(struct ifreq);  //number of network interfaces found              (i = 0; < ifc_num; i++)             {                  if(ifr[i].ifr_addr.sa_family != af_inet) //if not ipv4 address, nothing                 {                     continue;                 }                  if (strcmp(ifr[i].ifr_ifrn.ifrn_name,"eth0.32")==0)                 {                     if (ioctl(sd, siocgifaddr, &ifr[i]) == 0) // here ipv6 socket doesn't enter!!!                     {                         addr = ntohl(((struct sockaddr_in *)(&ifr[i].ifr_addr))->sin_addr.s_addr);                      }                      fclose(fp);                      break;  // end loop                 }             }         }     }     return addr;  } 

thanks in advance help!

you should using getifaddrs not ioctl siocgifaddr.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -