如何确定传入连接来自本地计算机 [英] How to determine an incoming connection is from local machine

查看:72
本文介绍了如何确定传入连接来自本地计算机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SocketServer接受传入的连接.出于安全原因,我只应允许本地连接(来自运行服务器的计算机的连接).

I have a SocketServer accepting incoming connections. For security reasons I should only allow local connections (connections from the machine on which server is running).

如何确定传入连接是否来自另一台计算机?下列代码对此安全吗?

How can I determine if an incoming connection is from another machine? Is the following code safe for this?

Socket socket = someServerSocket.accept();
String remoteAddress = socket .getInetAddress().getHostAddress();
if (!fromThisMachine(remoteAddress)) {
    // Not from this machine.
}

fromThisMachine()方法是这样的:

public boolean fromThisMachine(String remoteAddress) {
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress inetAddress = addresses.nextElement();
                String hostName = inetAddress.getHostName();
                String hostAddr = inetAddress.getHostAddress();
                if (hostName.equals(remoteAddress) || hostAddr.equals(remoteAddress)) {
                    return true;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    log("Unauthorized request to server from: " + remoteAddress);
    return false;
}

谢谢, 莫森

推荐答案

如果要限制来自本地主机的连接,请在打开ServerSocket时指定该连接.如果仅在localhost上侦听,则只能从localhost获得连接.

If you want to limit connections from the localhost, then specify that when you open the ServerSocket. If you only listen on localhost, then you'll only get connections from localhost.

    int port = .....
    SocketAddress socketAddress = new InetSocketAddress("127.0.0.1", port);
    ServerSocket serverSocket = new ServerSocket();
    serverSocket.bind(socketAddress);
    serverSocket.accept();

这篇关于如何确定传入连接来自本地计算机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆