简体   繁体   中英

how to get ipv4 and ipv6 packets using the same socket in Windows, it was working on linux

int m_nSocket6;
sockaddr_in6 m_address_6;

/*created the socket*/

m_nSocket6 = socket(AF_INET6, SOCK_DGRAM, 0);

int ret;
/* Set socket buffer size */

    int buffer_size;

   ret = setsockopt(m_nSocket, SOL_SOCKET, SO_RCVBUF, (char*) &buffer_size, sizeof(buffer_size));

/* Set socket timeout */

    int timeout = m_nTimeout;
    ret = setsockopt(m_nSocket, SOL_SOCKET, SO_RCVTIMEO, (char*) &timeout, sizeof(timeout));

/*Multicast*/

int yes = m_nMulticast; //1 = enabled
    ret = setsockopt(m_nSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));

/*bind*/

     memset((char *)&abc, 0, sizeof(m_address6));
     m_address6.ss_family = AF_UNSPEC;
     m_address6.sin6_family = AF_INET6;
     m_address_6.sin6_addr = in6addr_any;
     m_address6.sin6_port = htons((u_short)m_nPort);
     ret = bind(m_nSocket6, (struct sockaddr*) &abc, sizeof(abc));

/*receiving the packets*/

recvfrom(m_nSocket, m_sBuffer, UPD_DATAGRAM_BUFFER_SIZE, 0, (struct sockaddr*) &m_address, &server_length);

In order to work with both IPv4 and IPv6 traffic with a single socket, you must create a dual-stack socket , which is an IPv6 socket that has the IPV6_V6ONLY option disabled.

Refer to MSDN documentation for more details:

Dual-Stack Sockets for IPv6 Winsock Applications

In order to support both IPv4 and IPv6 on Windows XP with Service Pack 1 (SP1) and on Windows Server 2003, an application has to create two sockets, one socket for use with IPv4 and one socket for use with IPv6. These two sockets must be handled separately by the application.

Windows Vista and later offer the ability to create a single IPv6 socket which can handle both IPv6 and IPv4 traffic . For example, a TCP listening socket for IPv6 is created, put into dual stack mode, and bound to port 5001. This dual-stack socket can accept connections from IPv6 TCP clients connecting to port 5001 and from IPv4 TCP clients connecting to port 5001. This feature allows for greatly simplified application design and reduces the resource overhead required of posting operations on two separate sockets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM