Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ แปลงที่อยู่ IP Address เป็นเลขฐานสิบหก (Hexadecimal)


บทนำ

แปลงที่อยู่ IP Address (IPv4) เป็นค่า Hexadecimal

IP Address คืออะไร?

หมายเลขระบุตัวตนอุปกรณ์บนเครือข่าย รูปแบบ IPv4: 4 กลุ่มตัวเลขคั่นด้วยจุด เช่น 151.101.65.121

ตัวอย่าง

  • 127.0.0.1 → 0x7f000001
  • 172.31.0.2 → 0xac1f0002

ตัวอย่างโค้ด C++ (ใช้ <arpa/inet.h>)

#include <arpa/inet.h>
#include <iostream>
#include <string.h>
using namespace std;

void reverse(char* str) {
    int len = 2;
    int r = strlen(str) - 2;
    while (len < r) {
        swap(str[len++], str[r--]);
        swap(str[len++], str[r]);
        r -= 3;
    }
}

void convert(int ip_add) {
    char str[15];
    sprintf(str, "0x%08x", ip_add);
    reverse(str);
    cout << str << "\n";
}

int main() {
    int ip_add = inet_addr("127.0.0.1");
    convert(ip_add);
    return 0;
}

ผลลัพธ์

0x7f000001