使用IPv6在Java中进行Socket编程

huangapple go评论80阅读模式
英文:

Socket Programming in Java using IPv6

问题

以下是您要的翻译内容:

我对网络编程还不熟悉,有几个问题在任何地方都找不到答案。
我不明白在建立连接时,IPv4和IPv6之间的代码是否有区别。

示例代码:
Socket socket = new Socket(“127.0.0.1”, 5000)

上述代码用于IPv4,据我理解。但如果我想使用IPv6,我该如何初始化套接字?

英文:

I am new with the network programming and I have a few questions, that I couldn't find anywhere.
I don't understand if there is a difference in code between IPv4 and IPv6, when establishing connection.

Example Code :
Socket socket = new Socket(“127.0.0.1”, 5000)

The above code is used for IPv4, as I understood. But how do I initialize the socket if I want to use IPv6?

答案1

得分: 0

I don't understand if there is a difference in code between IPv4 and IPv6, when establishing connection.

There is little difference.

  • If you want to use an explicit IPv6 address, you will typically just instantiate the Socket with an IP address string in IPv6 syntax.

  • If you use a DNS name, then the available network stacks will determine whether you use IPv4 or IPv6:

    • If only one stack is supported (by the OS) and available, that is used.
    • If both stacks are available, the setting of the java.net.preferIPv4Stack property determines which is used.

For more information, read Networking IPv6 User Guide from the Oracle Java documentation.

For example this: Socket socket = new Socket("127.0.0.1", 5000) is used for IPv4, as I understood. But how do I initialize the socket if I want to use IPv6?

Socket socket = new Socket("::1", 5000);

See also: https://stackoverflow.com/questions/40189084/what-is-ipv6-for-localhost-and-0-0-0-0

英文:

> I don't understand if there is a difference in code between ipv4 and ipv6, when establishing connection.

There is little difference.

  • If you want to use an explicit IPv6 address, you will typically just instantiate the Socket with a IP address string in IPv6 syntax.

  • If you use a DNS name, then the available network stacks will determine whether you use IPv4 or IPv6:

    • If only one stack is supported (by the OS) and available, that is used.
    • If both stacks are available, the setting of the java.net.preferIPv4Stack property determines which is used.

For more information, read Networking IPv6 User Guide from the Oracle Java documentation.

> For example this: Socket socket = new Socket("127.0.0.1", 5000) is used for ip4, as I understood. But how do I initialize the socket if I want to use ip6?

Socket socket = new Socket("::1", 5000);

See also: https://stackoverflow.com/questions/40189084/what-is-ipv6-for-localhost-and-0-0-0-0

huangapple
  • 本文由 发表于 2020年9月8日 15:58:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63789563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定