LoginSignup
8
4

More than 5 years have passed since last update.

ArduinoでIPアドレス取得時に4オクテット記法へ変換するTips

Posted at

こんにちわ。

小ネタです。

Arduinoで.localIP()とかのIPアドレス拾うやつ、お馴染みのxxx.xxx.xxx.xxx`へ変換するのはちょっと小細工が必要だったのでメモって置きます。

// 例: 192.168.0.13 の場合
(String)WiFi.localIP();

// そのままStringにcastすると...
// => "218147008"

// "218147008"を2進にすると...
// 00001101 00000000 10101000 11000000

// 8bitずつ10進にすると...
//       13        0      168      192

// お分かり頂けただろうか...

// つまりこうじゃ!
String ipToString(uint32_t ip){
    String result = "";

    result += String((ip & 0xFF), 10);
    result += ".";
    result += String((ip & 0xFF00) >> 8, 10);
    result += ".";
    result += String((ip & 0xFF0000) >> 16, 10);
    result += ".";
    result += String((ip & 0xFF000000) >> 24, 10);

    return result;
}

Serial.println(ipToString(WiFi.localIP()));
// => "192.168.0.13"

// パワープレイは正義。めでたしめでたし。
8
4
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
8
4