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

วิธีหา IP Address ของคอมพิวเตอร์โลคอลด้วย C/C++

บทนำ

ในส่วนนี้เราจะดูวิธีดูชื่อโฮสต์ (Host name) และ IP Address ของระบบโลคอลอย่างง่าย เราจะเขียนโปรแกรม C เพื่อหาชื่อโฮสต์และ IP

ฟังก์ชันที่ใช้

ลำดับ ฟังก์ชันและคำอธิบาย
1 gethostname()
หาชื่อโฮสต์มาตรฐานของคอมพิวเตอร์โลคอล
2 gethostbyname()
หาข้อมูลโฮสต์ที่สอดคล้องกับชื่อโฮสต์จากฐานข้อมูลโฮสต์
3 inet_ntoa()
แปลงที่อยู่เครือข่าย IPv4 เป็นสตริง ASCII ในรูปแบบทศนิยมจุด

ตัวอย่างโค้ด C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void check_host_name(int hostname) {
    if (hostname == -1) {
        perror("gethostname");
        exit(1);
    }
}

void check_host_entry(struct hostent *hostentry) {
    if (hostentry == NULL) {
        perror("gethostbyname");
        exit(1);
    }
}

void IP_formatter(char *IPbuffer) {
    if (NULL == IPbuffer) {
        perror("inet_ntoa");
        exit(1);
    }
}

int main() {
    char host[256];
    char *IP;
    struct hostent *host_entry;
    int hostname;
    hostname = gethostname(host, sizeof(host));
    check_host_name(hostname);
    host_entry = gethostbyname(host);
    check_host_entry(host_entry);
    IP = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0]));
    printf("Current Host Name: %s\n", host);
    printf("Host IP: %s\n", IP);
    return 0;
}

ผลลัพธ์

Current Host Name: soumyadeep-VirtualBox
Host IP: 127.0.1.1