【发布时间】:2010-12-05 06:32:50
【问题描述】:
我有一个接受传入连接的 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;
}
谢谢, 莫森
【问题讨论】:
标签: java networking sockets network-programming