Mina Get client IP address problem __mina

Source: Internet
Author: User
Tags sessions

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");
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.