好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java 伪造http请求ip地址的方法

最近做接口开发,需要跟第三方系统对接接口,基于第三方系统接口的保密性,需要将调用方的请求ip加入到他们的白名单中。由于我们公司平常使用的公网的ip是不固定的,每次都需要将代码提交到固定的服务器上(服务器ip加入了第三方系统的白名单),频繁的修改提交合并代码和启动服务器造成了额外的工作量,给接口联调带来了很大的阻碍。

正常的http请求

我们正常发起一个http的请求如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

import org.apache.http.httpentity;

import org.apache.http.client.config.requestconfig;

import org.apache.http.client.methods.closeablehttpresponse;

import org.apache.http.client.methods.httppost;

import org.apache.http.entity.stringentity;

import org.apache.http.impl.client.closeablehttpclient;

import org.apache.http.impl.client.httpclients;

import org.apache.http.util.entityutils;

 

public static string getpost4json(string url, string json) throws exception {

   closeablehttpclient httpclient = httpclients.createdefault();

   httppost httppost = new httppost(url);

   /* 设置超时 */

   requestconfig defaultrequestconfig = requestconfig.custom().setsockettimeout( 5000 ).setconnecttimeout( 5000 ).setconnectionrequesttimeout( 5000 ).build();

   httppost.setconfig(defaultrequestconfig);

   httppost.addheader( "content-type" , "application/json;charset=utf-8" );

   httppost.setentity( new stringentity(json, "utf-8" ));

   closeablehttpresponse response = null ;

   string result = null ;

   try {

     response = httpclient.execute(httppost);

     httpentity entity = response.getentity();

     result = entityutils.tostring(entity, "utf-8" );

   } catch (exception e) {

     throw e;

   } finally {

     if (response != null ) response.close();

     httpclient.close();

   }

   return result;

}

由于没有加入白名单的原因,这样的请求显然无法调用到第三方的接口。这时候考虑能否将请求的ip改为白名单的一个ip,服务器在解析时拿到的不是正常的ip,这样能否正常调用呢?

伪造http请求ip地址

我们知道正常的tcp/ip在通信过程中是无法改变源ip的,也就是说电脑获取到的请求ip是不能改变的。但是可以通过伪造数据包的来源ip,即在http请求头加一个x-forwarded-for的头信息,这个头信息配置的是ip地址,它代表客户端,也就是http的请求端真实的ip。因此在上面代码中加上如下代码:

?

1

httppost.addheader( "x-forwarded-for" ,ip);

服务端通过x-forwarded-for获取请求ip,并且校验ip安全性,代码如下:

?

1

string ip = request.getheader( "x-forwarded-for" );

总结

通过请求头追加x-forwarded-for头信息可以伪造http请求ip地址。但是若服务器不直接信任并且不使用传递过来的 x-forward-for 值的时候伪造ip就不生效了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://segmentfault.com/a/1190000016537618

查看更多关于java 伪造http请求ip地址的方法的详细内容...

  阅读:24次