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

โปรแกรมแสดง Hostname และ IP Address ใน C

ใช้ฟังก์ชันเครือข่ายเพื่อดึงชื่อโฮสต์และ IP Address ของเครื่องท้องถิ่น

ฟังก์ชันหลัก

ฟังก์ชันคำอธิบาย
gethostname()หาชื่อโฮสต์มาตรฐานของคอมพิวเตอร์ท้องถิ่น
gethostbyname()หาข้อมูลโฮสต์จากฐานข้อมูลโดยใช้ชื่อโฮสต์
inet_ntoa()แปลง IPv4 Address เป็นสตริงรูปแบบ Dotted Decimal

ตัวอย่าง

#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 = 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