C Program to Display Hostname And IP Address

In this program, we will share how to get the Hostname and IP address of a local machine. In this program, I am using these predefined functions:

1) gethostname(): Get the hostname of a local machine.2) gethostbyname(): Get the host information corresponding to the hostname.3) inet_ntoa(): This function will convert an (Ipv4) Internet network address into an ASCII string in decimal format.

C Program to display hostname and IP address

Copy the below c program and execute it with the help of c compiler.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

// C program to display hostname

// and IP address

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

// Returns hostname for the local computer

voidcheckHostName(inthostname)

{

if(hostname==-1)

{

perror("gethostname");

exit(1);

}

}

// Returns host information corresponding to host name

voidcheckHostEntry(structhostent*hostentry)

{

if(hostentry==NULL)

{

perror("gethostbyname");

exit(1);

}

}

// Converts space-delimited IPv4 addresses

// to dotted-decimal format

voidcheckIPbuffer(char*IPbuffer)

{

if(NULL==IPbuffer)

{

perror("inet_ntoa");

exit(1);

}

}

// Driver code

intmain()

{

charhostbuffer[256];

char*IPbuffer;

structhostent*host_entry;

inthostname;

// To retrieve hostname

hostname=gethostname(hostbuffer,sizeof(hostbuffer));

checkHostName(hostname);

// To retrieve host information

host_entry=gethostbyname(hostbuffer);

checkHostEntry(host_entry);

// To convert an Internet network

// address into ASCII string

IPbuffer=inet_ntoa(*((structin_addr*)

host_entry->h_addr_list[0]));

printf("Hostname: %s\n",hostbuffer);

printf("Host IP: %s",IPbuffer);

return0;

}

Output of program:

Hostname: cContainer Host IP: 10.98.162.101

Share this post:

Related Tutorials

About: Prem Tiwari

Prem Tiwari is the founder of FreeWebMentor.com and also a professional developer who has vast experience in PHP and open source technologies. Apart from this, he is a blogger by hobby and also he has been a regular speaker of WordPress sessions in various IT Companies. View all posts by Prem Tiwari

Subscribe my updates via Email

We use cookies to ensure that we give you the best experience and deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.OkPrivacy policy