C Program to display hostname and IP address

In C, we can retrieve the hostname and IP address of the local system using socket programming functions. This is useful for network programming and system administration tasks.

Syntax

int gethostname(char *name, size_t len);
struct hostent *gethostbyname(const char *name);
char *inet_ntoa(struct in_addr in);

Key Functions

Function Description
gethostname() Retrieves the standard hostname for the local computer
gethostbyname() Finds host information corresponding to a hostname from host database
inet_ntoa() Converts an IPv4 network address into ASCII dotted decimal format
Note: This program requires compilation with network libraries. On Linux systems, use: gcc -o program program.c

Example

The following program demonstrates how to get the hostname and IP address of the local system −

#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_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;
    
    // Find the hostname
    hostname = gethostname(host, sizeof(host));
    check_host_name(hostname);
    
    // Find host information
    host_entry = gethostbyname(host);
    check_host_entry(host_entry);
    
    // Convert to IP string
    IP = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0]));
    IP_formatter(IP);
    
    printf("Current Host Name: %s
", host); printf("Host IP: %s
", IP); return 0; }

Output

Current Host Name: localhost
Host IP: 127.0.0.1

How It Works

  • gethostname() retrieves the system's hostname into a character buffer
  • gethostbyname() queries the host database to get detailed host information
  • inet_ntoa() converts the binary IP address to readable dotted decimal notation
  • Error checking functions ensure proper handling of network operation failures

Conclusion

This program demonstrates basic network programming in C by retrieving local system information. The combination of hostname and IP retrieval functions provides essential system identification capabilities for network applications.

Updated on: 2026-03-15T10:07:28+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements