[PYTHON] [PHP] Obtain the source IP address when POST is sent from an IoT device [ESP32]

Introduction

This is for those who are trying to identify IoT devices using IP addresses and those who want to obtain the IP address of the device on the server side.

environment

--IoT device (ESP32) --Firmware (MicroPython1.3) --Server (Ubuntu18.04) --Web server (Apache2)

Source code (ESP32)

This time, I made a program that POSTs appropriate JSON data with ESP32, acquires the IP address of the source on the server, and returns that IP address as a response.

post.py


import urequests
import ujson

#Specifying the destination URL
#"XXX.XXX.XXX.XXX"Put the URL in
url = 'http://XXX.XXX.XXX.XXX/receive.php'

#Declare data as DICT type
obj = {"value" : 123, "text" : "abc"}

#Explicitly declare that it will be sent as json data
header = {'Content-Type' : 'application/json'}

#Convert object to JSON and send HTTP request as POST
res = urequests.post(
    url,
    data = ujson.dumps(obj).encode("utf-8"),
    headers = header
)

#Receives and displays the response from the server side(I also decode json)
print (res.json())

#End
res.close()

Source code (server)

The source IP address is in $ _SERVER [REMOTE_ADDR], so put it in a variable.

receive.php


<?php
//Receive the sent POST data, decode the JSON data$Put in in.
$json_string = file_get_contents('php://input');
$in = json_decode(stripslashes($json_string),true);

//Extract the sent data
$value = $in["value"]; // = 123
$text = $in["text"];   // = abc

//$_Use the SERVER variable to get the source IP address
//Use the IP address from which the response was obtained, and re-encode it as JSON.
//And the sender(ESP32)Return to.
$ipAddress = $_SERVER['REMOTE_ADDR'];
//If you are using AWS ELB, you will get the IP address of ELB.
//Get the original IP address as follows
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
        $ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
}
//Encode and return the IP address
echo json_encode($ipAddress);
?>

Execution result

When I ran it with micropython's WEB REPL, the IP address was returned.

>>> execfile("post.py")
>>> YYY.YYY.YYY.YYY // <-IP address of ESP32

reference

This article is written with reference to the following articles

[1] Send data from ESP32 by HTTP request (POST) with Micropython and receive it with PHP (server)

Recommended Posts

[PHP] Obtain the source IP address when POST is sent from an IoT device [ESP32]