POSIX सॉकेट API (gethostname, gethostbyname, inet_ntoa) का उपयोग करके स्थानीय होस्टनाम और IPv4 एड्रेस प्राप्त करें।
आवश्यक हेडर्स
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h>
पूर्ण उदाहरण
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void check_error(int val, const char *msg) {
if (val == -1) {
perror(msg);
exit(EXIT_FAILURE);
}
}
int main() {
char host[256];
struct hostent *host_entry;
char *ip;
// होस्टनाम प्राप्त करें
check_error(gethostname(host, sizeof(host)), "gethostname");
// होस्ट एंट्री प्राप्त करें
host_entry = gethostbyname(host);
if (!host_entry) {
herror("gethostbyname");
exit(EXIT_FAILURE);
}
// पहला IPv4 एड्रेस प्राप्त करें
ip = inet_ntoa(*(struct in_addr*)host_entry->h_addr_list[0]);
if (!ip) {
perror("inet_ntoa");
exit(EXIT_FAILURE);
}
printf("Hostname: %s\n", host);
printf("IP Address: %s\n", ip);
return 0;
}
आउटपुट
Hostname: mymachine IP Address: 192.168.1.100
महत्वपूर्ण नोट्स
gethostbyname**अप्रचलित** है (POSIX.1-2001)। आधुनिक कोडgetaddrinfoउपयोग करे।inet_ntoaथ्रेड-सेफ नहीं है (स्टैटिक बफर रिटर्न करता है)।inet_ntopउपयोग करें।- यह केवल पहला IPv4 एड्रेस दिखाता है। मल्टी-होम्ड सिस्टम्स के लिए सभी एड्रेसेज़ इटरेट करें।
- विंडोज पर:
Winsock2.hलिंक करें,WSAStartup/WSACleanupकॉल करें।
आधुनिक विकल्प (getaddrinfo)
// getaddrinfo संस्करण IPv4/IPv6 दोनों सपोर्ट करता है // अधिक जटिल लेकिन मानक-अनुरूप और थ्रेड-सेफ