Search code examples
cnetwork-programmingserveripv6ipv4

Server binding results in error "Cannot assign requested address"?


I would like to create a server on localhost, using IPv6 mapped IPv4 address of the local host, but I get errno 99. I am not sure what am I doing wrong here:

#define IPv6_MAPPED_IPv4_LOCAL_ADDRESS "::FFFF:127.0.0.1" //localhost
#define PORT 12345

 static int server()
 {
   int fd, v6only;
   struct sockaddr_in6 addr6;

   v6only = 0;
   /* IPv6 TCP socket */
   fd = socket(AF_INET6, SOCK_STREAM, 0);
   if (fd == -1) {
       fprintf(stderr, "Creating tcp socket failed \n");
       return -1;
    }

   memset(&addr6, 0, sizeof(struct sockaddr_in6));
   addr6.sin6_family = AF_INET6;
   memcpy(addr6.sin6_addr.s6_addr, IPv6_MAPPED_IPv4_LOCAL_ADDRESS, sizeof(struct in6_addr));
   addr6.sin6_port = htons(PORT);
   addr6.sin6_scope_id = 0;

   /* use setsockopt() to enable dual stack on the server */
   if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only)) < 0) {
        fprintf(stderr, "Setting IPV6_V6ONLY to 0 failed error %s \n", strerror(errno)); 
        close(fd);
        return -1;
    }

   /* bind server socket to the address */
   if (bind(fd, (struct sockaddr *)&addr6, sizeof(struct sockaddr_in6)) < 0) {  
       fprintf(stderr, "Binding socket failed error %s\n", strerror(errno));
       close(fd);
       return -1;
   }
 }

The server fails with the error Binding socket failed error Cannot assign requested address


Solution

  • addr6.sin6_addr.s6_addr is not the address as a string but as a binary format. you need to convert the string to this binary format using inet_pton.

    As in

    inet_pton(AF_INET6, IPv6_MAPPED_IPv4_LOCAL_ADDRESS, &addr6.sin6_addr.s6_addr);