When using Mina to do socket communication, the server side gets the client IP address, which is actually very simple, the code is as follows:
@Overridepublic void Messagereceived (iosession session, Object message) throws Exception { String ClientIP = ((Inetso cketaddress) session.getremoteaddress ()). GetAddress (). gethostaddress ();
But sometimes it turns out that session.getremoteaddress () is null, unable to get to the client IP address, what's going on?
Later, the data found that the reason is that if the client sends the message, immediately after the connection to the socket 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 follow the specified rules, so how do you solve this problem?
In fact, the solution is 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:
@Overridepublic 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);}
Get the client IP address:
@Overridepublic void Messagereceived (iosession session, Object message) throws Exception { string clientip = (string) Session.getattribute ("Key_session_client_ip");}
Mina getting client IP address issues