[英]How to determine an incoming connection is from local machine
I have a SocketServer accepting incoming connections. 我有一个SocketServer接受传入的连接。 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.
}
while fromThisMachine()
method is like this: 而
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;
}
Thanks, Mohsen 谢谢,Mohsen
InetAddress.getByName( null ) always returns the loopback address. InetAddress.getByName(null)始终返回环回地址。 See the javadoc
请参阅javadoc
int port = .....
SocketAddress socketAddress =
new InetSocketAddress( InetAddress.getByName( null ), port);
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(socketAddress);
serverSocket.accept();
If you want to limit connections from the localhost, then specify that when you open the ServerSocket. 如果要限制来自localhost的连接,请在打开ServerSocket时指定。 If you only listen on localhost, then you'll only get connections from localhost.
如果您只在localhost上侦听,那么您将只从localhost获取连接。
int port = .....
SocketAddress socketAddress = new InetSocketAddress("127.0.0.1", port);
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(socketAddress);
serverSocket.accept();
Thanks skaffman. 谢谢skaffman。 The following code worked with a little manipulation (hard-coding 127.0.0.1).
以下代码使用了一点操作(硬编码127.0.0.1)。
int port = .....
SocketAddress socketAddress = new InetSocketAddress("127.0.0.1", port);
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(socketAddress);
serverSocket.accept();
If I read local address from InetAddress.getLocalHost(), other network users on the same subnet are still able to see my server. 如果我从InetAddress.getLocalHost()读取本地地址,则同一子网上的其他网络用户仍然可以看到我的服务器。
Mohsen. 穆赫辛。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.