简体   繁体   中英

pre-creating sockets without knowing whether they are IPv4 or IPv6

I have some code which works by pre-creating sockets (via. socket() BSD API), and then at a later time when the address is known it will do the connect() etc. This works with IPv4 but now I am refactoring to support IPv6 as well.

The problem is that it seems that when I do the initial socket() I need to put in AF_INET or AF_INET6. However since I don't know the address yet I don't know which is correct. Is there anyway to create a generic socket which will work for either? If I use AF_INET6 and I am on a IPv4 network, am I correct in assuming it will not work?

A related question - Even though I don't know the IP address yet, is it possible I can detect what network my device is on: IPv4 or IPv6? Assuming one network interface, I think I can only be one of those networks, so if I can find a way to detect what type of network my device is on, then I can do that at socket creation time.

Another option is to refactor to create the socket only when I know the address, but there is a big codebase and I would like to avoid that if possible.

I'm writing code that runs on iOS, but I am not sure if that is relevant here.

What you want to do is not possible. When socket is created, it is associated with stack protocol, and IPV6 and IPV4 are just different stack protocols.

However, the real question is why do you precreate sockets? Why not create the socket when you need to?

And last, but not the least, your assumption is incorrect. Your device can have multiple interfaces - one for IPv4, another for IPv6 - and use them both.

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