获取用户IP的正确方法

时间:2019-09-26 05:20:59

标签: java spring tomcat ip

我有以下应获取用户IP的代码:

public String getUserIP()
{
   Object details = getDetails();
   if (details instanceof WebAuthenticationDetails)
   {
     return ((WebAuthenticationDetails)details).getRemoteAddress();
   }
   return "";
}

@Nullable
public Object getDetails()
{
   Authentication authentication = getCurrentUserAuth();
   return authentication != null ? authentication.getDetails() : null;
}

但是,在某些未知情况下,它将返回127.0.0.1而不是真实IP。

我决定像这样重写:

public String getUserIP() 
{
  ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
  HttpServletRequest request = attr.getRequest();

  String ip = request.getHeader("X-Forwarded-For").split(',')[0]; 

  return ip;
}

但是在某些情况下,标头X-Forwarded-For为空。仅在第一个代码段中的getUserIP()返回有效IP地址的情况下才会发生该异常。有什么问题? Web服务器是tomcat。预先感谢。

2 个答案:

答案 0 :(得分:0)

您可以像这样更新。


public String getUserIP() 
{
  ServletRequestAttributes attr = (ServletRequestAttributes) 
  RequestContextHolder.currentRequestAttributes();
  HttpServletRequest request = attr.getRequest();
  return request.getRemoteAddr();
}

答案 1 :(得分:0)

您可以尝试

import React from 'react';

import {Text, View, Button, StyleSheet, TextInput, TouchableOpacity} from "react-native";

export default class AddKidScreen extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            name: '',
            age: '',
            parentID: props.navigation.getParam('myID', 0)
        }
    }

    handleAddKid() {
        let url = "https://piotr2.scementowani.pl/apiPiotr";
        let name = this.state.name;
        let age = this.state.age;
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': "application/json",
            },
            body: JSON.stringify({
                method: "addKid",
                name: name,
                age: age,
            }),
        })
            .then(response => response.json())
            .then(responseJson => {
                this.props.navigation.navigate('Main');
            })
            .catch((error) => {
                console.error(error);
            });
    }

    updateValue(text,field) {
        if (field == 'name') {
            this.setState({
                name: text,
            })
        } else if (field == 'age' ){
            this.setState( {
                age: text,
            })
        }
    }

    render() {
        return(
            <View>
                <View style={{flexDirection: 'row', width: '100%'}}>
                    <Text>
                        Imię:
                    </Text>
                    <TextInput
                        placeholder = "Imię"
                        onChange = {(text) => this.updateValue(text,'name')}
                    />
                </View>
                <View style={{flexDirection: 'row', width: '100%'}}>
                    <Text>
                        Wiek:
                    </Text>
                    <TextInput
                        placeholder = "Wiek"
                        onChange = {(text) => this.updateValue(text,'age')}
                    />
                </View>
                <TouchableOpacity onPress={this.handleAddKid.bind(this)}>
                    <Text>DODAJ</Text>
                </TouchableOpacity>
            </View>
        )
    }
}

}