简体   繁体   English

在JavaFX桌面应用程序中获取远程IP地址

[英]Get remote IP address in JavaFX desktop app

I need to obtain the remote IP address of a user in my JavaFX desktop app. 我需要在JavaFX桌面应用程序中获取用户的远程IP地址。 I am using Spring to deal with things such as authentication (my program uses database connection). 我正在使用Spring处理诸如身份验证之类的事情(我的程序使用数据库连接)。 I do know how to get IP address from http request when using Java Servlet, the problem is I don't have one in my app. 我确实知道在使用Java Servlet时如何从http请求获取IP地址,问题是我的应用程序中没有IP地址。 I considered using some kind of website that checks IP, and simply getting the content of the html parsed to a string, but I have to do everything locally / independent from any external source. 我考虑过使用某种类型的网站来检查IP,只是将html的内容解析为字符串,但是我必须在本地/独立于任何外部资源来完成所有工作。

I appreciate any kind of help, thanks in advance 感谢您的帮助,在此先感谢

EDIT: Some additional info that might help: I am not using sockets, my app is supposed to be used by end user, and only connection it has is the connection with MySQL database from which it gets some content. 编辑:一些其他信息可能会有所帮助:我不使用套接字,我的应用程序应由最终用户使用,并且只有它具有的连接是与MySQL数据库的连接,从中可以获取一些内容。 I need to retrieve the IP address of user at the moment of logging in, to put said IP address together with port to a particular table in my database. 我需要在登录时检索用户的IP地址,以将所述IP地址和端口一起放入数据库中的特定表。

As suggested in the comments, the only way to do this is to query an external source. 如评论中所建议,唯一的方法是查询外部源。 You can fairly easily write some code to do this, eg 您可以相当容易地编写一些代码来做到这一点,例如

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


public class RealIPScraper {
    private static final String URL_STRING = "http://www.realip.info/api/p/realip.php" ;

    private static final Pattern pattern = Pattern.compile("\\{\"IP\":\"(?<ip>.*)\"\\}");

    public static String getIP() throws IOException {
        URL url = new URL(URL_STRING);
        try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()))) {
            String content = String.join("\n", in.lines().collect(Collectors.toList()));
            Matcher matcher = pattern.matcher(content);
            if (matcher.matches()) {
                return matcher.group("ip");
            } else {
                return "No ip found";
            }
        }
    }

}

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

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