我有一个SocketServer接受传入的连接.出于安全原因,我应该只允许本地连接(来自运行服务器的计算机的连接).
如何确定传入连接是否来自其他计算机?以下代码是否安全?
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; }
谢谢,
穆赫辛
解决方法
如果要限制来自localhost的连接,请在打开ServerSocket时指定该连接.如果您只在localhost上侦听,那么您只能从localhost获取连接.
int port = ..... SocketAddress socketAddress = new InetSocketAddress("127.0.0.1",port); ServerSocket serverSocket = new ServerSocket(); serverSocket.bind(socketAddress); serverSocket.accept();