Java : forcer l'usage d'IPv4 et désactiver IPv6
jeu, 02/10/2025 - 11:30
Java supporte IPv4 et IPv6. L'environnement va alors utiliser l'un ou l'autre selon la configuration réseau et le système. Cependant, tout n'est pas parfait et il peut avoir des effets de bord à cause d'IPv6, par exemple sur des environnements anciens ou pas totalement compatible IPv6. Dans ce cas, la désactivation d'IPv6 peut être une solution, de facto, vous forcez l'usage d'IPv4.
Pour ce faire, il faut appeler une propriété système : java.net.preferIPv4Stack. Il faut la mettre en true, soit : java.net.preferIPv4Stack=true
Le code aura la forme suivante :
System.setProperty("java.net.preferIPv4Stack", "true");
Dans la documentation Oracle, nous trouvons l'explication suivante (référence Java 25) :
java.net.preferIPv4Stack (default: false)
If IPv6 is available on the operating system the underlying native socket will be, by default, an IPv6 socket which lets applications connect to, and accept connections from, both IPv4 and IPv6 hosts. However, in the case an application would rather use IPv4 only sockets, then this property can be set to true. The implication is that it will not be possible for the application to communicate with IPv6 only hosts.java.net.preferIPv6Addresses (default: false)
When dealing with a host which has both IPv4 and IPv6 addresses, and if IPv6 is available on the operating system, the default behavior is to prefer using IPv4 addresses over IPv6 ones. This is to ensure backward compatibility: for example, for applications that depend on the representation of an IPv4 address (e.g. 192.168.1.1). This property can be set to true to change that preference and use IPv6 addresses over IPv4 ones where possible, or system to preserve the order of the addresses as returned by the system-wide resolver.
En utilisant java.net.preferIPv4Stack à true, vous forcez donc l'application à utilisr IPv4 et à désactiver IPv6. Mais attention, assurez-vous que l'ensemble de l'environnement soit bien full compatible IPv4 pour éviter toute erreur réseau.

