Mina getting client IP address issues

Source: Internet
Author: User

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

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.