1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Arduino Web Server で クライアントのIPアドレスを取得する方法

Posted at

クライアントのIPアドレスを取得する方法

WebServer.hを使用

ネットで調べたが、ズバリのコードを見つけられなかったので、ソースコードを解読しながら 調べた結果を、備忘録として残しておく。

WebServer.hの使い方は 他の記事に譲るとして、
クライアントからリクエストを受けた時に、そのクライアントのIPアドレスを取得するコードを示す。(⭐️印)

コード

#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>

const char *ssid = "SSID";
const char *pass = "PASSWORD";

WebServer server(80);

void handleRoot() {
#ifdef ARDUINO_RASPBERRY_PI_PICO_W  
  //for Raspberry Pi Pico W / Pico 2 W
  WebServer::ClientType& client = server.client(); //⭐️
#else
  //for ESP32 / ESP32-S3 / ESP32-C3 
  NetworkClient& client = server.client();         //⭐️
#endif
  IPAddress client_ip = client.remoteIP();         //⭐️
  uint16_t client_port = client.remotePort();      //⭐️

  Serial.print("Client IP address: ");
  Serial.print(client_ip);
  Serial.print("\tport: ");
  Serial.println(client_port);

  server.send(200, "text/HTML", "OK\r\n");
}

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, pass);
  Serial.print("WiFi connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected.");
  Serial.print("Server IP address: ");
  Serial.println(WiFi.localIP());

  server.on("/", handleRoot);

  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}
  • Raspberry Pi Pico W / Pico 2 W の場合
    WebServer::ClientType& client = server.client();
     

  • ESP32 / ESP32-S3 / ESP32-C3 の場合
    NetworkClient& client = server.client();

実行例

21:47:51.976 -> WiFi connecting...
21:47:51.976 -> WiFi connected.
21:47:51.976 -> Server IP address: 192.168.0.9
21:47:51.976 -> HTTP server started
21:47:57.360 -> Client IP address: 192.168.0.12	port: 58805
21:48:02.746 -> Client IP address: 192.168.0.12	port: 58811



以上

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?