Java 为什么 request.getRemoteAddr() 根据上下文(post 查询或 ajax 查询)返回 ipv4 或 ipv6
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3118829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why request.getRemoteAddr() returns ipv4 or ipv6 depending on context (post query or ajax query)
提问by Jerome Cance
I've donne a web app with Spring/GWT that uses Flash to upload files.
我已经完成了一个带有 Spring/GWT 的 Web 应用程序,它使用 Flash 上传文件。
When I send an ajax request with GWT and try to get the user ip address, I get an ipv4 address like: 127.0.0.1
当我使用 GWT 发送 ajax 请求并尝试获取用户 ip 地址时,我得到一个 ipv4 地址,如:127.0.0.1
but when I upload my files with flash (and so a post request on the same webapp) I get an ipv6 address 0:0:0:0:0:0:0:1
但是当我用 flash 上传我的文件时(以及在同一个 webapp 上的发布请求)我得到一个 ipv6 地址 0:0:0:0:0:0:0:1
I use the same code to get the user ip which is:
我使用相同的代码来获取用户 ip,它是:
ServletRequestAttributes att = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
att.getRequest().getRemoteAddr();
The problem is that I use a signature which uses the ip address to be sure that user can upload files (due to bug with session lost when uploading with flash) and the ip address changes when I use ajax or Post via flash.
问题是我使用了一个签名,它使用 ip 地址来确保用户可以上传文件(由于使用 flash 上传时会话丢失的错误),并且当我使用 ajax 或通过 flash 发布时,ip 地址会发生变化。
What's the problem and how can I get the same ip format ?
有什么问题,我怎样才能获得相同的 ip 格式?
thanks
谢谢
采纳答案by Ted Bigham
You can fix it by starting your server with this flag
您可以通过使用此标志启动服务器来修复它
-Djava.net.preferIPv4Stack=true
回答by unbeli
The reason is that the name you type in your browser has both ipv4 and ipv6 addresses. Browser chooses to use ipv4, flash chooses to use ipv6. There is nothing you can do about that on the server side (there is no way to convert).
However, you can change your DNS and make your name have only one address, either ipv4 or ipv6. You can also connect with a literal IP address (127.0.0.1), not a name (localhost).
原因是您在浏览器中键入的名称同时具有 ipv4 和 ipv6 地址。浏览器选择使用ipv4,flash选择使用ipv6。在服务器端对此您无能为力(无法进行转换)。
但是,您可以更改您的 DNS 并使您的名字只有一个地址,即 ipv4 或 ipv6。您还可以使用文字 IP 地址 (127.0.0.1) 而不是名称 (localhost) 进行连接。
回答by vikash kumar
you get an IPv6 address then IPv6 is being used. IPv4 and IPv6 are different protocols, and the client chooses which one to use when both are available.
您获得一个 IPv6 地址,然后正在使用 IPv6。IPv4 和 IPv6 是不同的协议,当两者都可用时,客户端选择使用哪一种。
If you want the client's IPv4 address then you can force them to use it by not advertising the IPv6 address in DNS. That would be a bad idea though with the increasing deployment of IPv6. Supporting both is good, so it is better to deal with clients using IPv6.
如果您想要客户端的 IPv4 地址,那么您可以通过不在 DNS 中通告 IPv6 地址来强制他们使用它。尽管随着 IPv6 部署的增加,这将是一个坏主意。支持两者都很好,所以最好处理使用 IPv6 的客户端。