How to determine a user's IP address in node

后端 未结 19 871
天命终不由人
天命终不由人 2020-11-22 12:46

How can I determine the IP address of a given request from within a controller? For example (in express):

app.post(\'/get/ip/address\', function (req, res) {         


        
相关标签:
19条回答
  • 2020-11-22 13:27

    If you are using Graphql-Yoga you can use the following function:

    const getRequestIpAddress = (request) => {
        const requestIpAddress = request.request.headers['X-Forwarded-For'] || request.request.connection.remoteAddress
        if (!requestIpAddress) return null
    
        const ipv4 = new RegExp("(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")
    
        const [ipAddress] = requestIpAddress.match(ipv4)
    
        return ipAddress
    }

    0 讨论(0)
提交回复
热议问题