Nodejs getting the client IP address

Source: Internet
Author: User
Tags node server

Why to get client IP:

PHP: We need to get the IP information of the user client to identify the user location, but now we get the address is always Hangzhou front-end: I check, a little wait .... Understand, we added a layer node server, the server in Hangzhou, you get the node server ipphp: What to do? Front end: I'll give you an IP field. php: Oh, the front end: (crackling ...) Okay, do you have a look at the value? PHP: Yes, but the value is not right, you pass to me is  :: FFFF:127.0. 0.1

Analysis Reason:

The IP field value of the front-end to PHP is req.connection.remoteAddress , theoretically nothing wrong, but actually get is IPv6 address, PHP need IPv4 address.

Nodejs website API:

NET Module Lookup Server.listen ()

Server.listen ([port][, host][, backlog][, callback])

Start a TCP service to listen for the input port and host.

If host is omitted, if IPv6 is available, the server will receive a link based on unspecified IPv6 address (::), otherwise receive unspecified IPV4 address (0.0.0.0)

Modification Method:

Specifies that the host parameter is 0.0.0.0, which is listen (port, ' 0.0.0.0 ', () = {});

For example:

Final Result:

Front End: Yes, you can look at PHP: I'll try ~ wait ... ok,bingo.

Summarizes a method of acquiring IP:

/** *function  getclientip (req    ) {return//  Determine if there is a reverse proxy IP        // determine the IP of the connection remote IP        //  judgment backend socket         req.connection.socket.remoteAddress;};

Nodejs getting the client IP address

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.