简体   繁体   English

使用 IPv6 的 Java 套接字编程

[英]Socket Programming in Java using 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.在建立连接时,我不明白 IPv4 和 IPv6 之间的代码是否存在差异。

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

The above code is used for IPv4, as I understood.据我了解,上述代码用于 IPv4。 But how do I initialize the socket if I want to use IPv6?但是如果我想使用 IPv6,我该如何初始化套接字?

I don't understand if there is a difference in code between ipv4 and ipv6, when establishing connection.我不明白ipv4和ipv6在建立连接时是否有代码差异。

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 .如果要使用显式 IPv6 地址,通常只需使用IPv6 语法中的 IP 地址字符串实例化Socket

  • If you use a DNS name, then the available network stacks will determine whether you use IPv4 or IPv6:如果您使用 DNS 名称,则可用的网络堆栈将决定您使用 IPv4 还是 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.如果两个堆栈都可用,则java.net.preferIPv4Stack属性的设置确定使用哪个。

For more information, read Networking IPv6 User Guide from the Oracle Java documentation.有关更多信息,请阅读 Oracle Java 文档中的网络 IPv6 用户指南

For example this: Socket socket = new Socket("127.0.0.1", 5000) is used for ip4, as I understood.例如: Socket socket = new Socket("127.0.0.1", 5000)用于ip4,据我所知。 But how do I initialize the socket if I want to use ip6?但是如果我想使用ip6,我该如何初始化套接字呢?

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

See also: What is IPV6 for localhost and 0.0.0.0?另请参阅: localhost 和 0.0.0.0 的 IPV6 是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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