Use Mina to do socket communication, the server to obtain the client IP address, in fact very simple, the code is as follows:
@Override public
void messagereceived (iosession sessions, Object message) throws Exception {
String ClientIP = ((I netsocketaddress) session.getremoteaddress ()). GetAddress (). gethostaddress ();
}
But sometimes it turns out that session.getremoteaddress () is null and cannot get the client IP address, what's going on here.
Later found that the reason is this, if the client sent the message, immediately after the socket connection to perform a close () operation, then the server side using Session.getremoteaddress () to obtain is null.
It is not possible to require all clients connected to the server to do so in accordance with the specified rules, so how to solve this problem.
In fact, the solution is very simple: when creating a socket connection, the client's IP address is saved, and then in the Messagereceived () method to obtain, the code is as follows:
@Override public
void Sessioncreated (Iosession session) throws Exception {
String ClientIP = ( inetsocketaddress) session.getremoteaddress ()). GetAddress (). gethostaddress ();
Session.setattribute ("Key_session_client_ip", ClientIP);
Logger.debug ("sessioncreated, client IP:" + ClientIP);
}
To obtain the client IP address:
@Override public
void messagereceived (iosession sessions, Object message) throws Exception {
String ClientIP = (St Ring) Session.getattribute ("Key_session_client_ip");
}