An Internet Protocol address (IP address) is a numerical label assigned to each device connected to a computer network that uses the Internet Protocol for communication.
Algorithm
- Create array hostbuffer[256], char *IPBuffer, struct hostent *host_entry,hostname
- hostname = gethostname(hostbuffer, sizeof(hostbuffer))
- IPbuffer = inet_ntoa(*((struct in_addr*)host_entry->h_addr_list[0])) (Converts Internet network address to ASCII string)
hostnamechk(hostname)
host_entry = gethostbyname(hostbuffer) ( To get host info)
hostentrychk(host_entry)
Code
// C program to print 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
void hostnamechk(int hostname)
{
if (hostname == -1)
{
perror("gethostname");
exit(1);
}
}
// getting host information of the host name
void hostentrychk(struct hostent * hostentry)
{
if (hostentry == NULL)
{
perror("gethostbyname");
exit(1);
}
}
// Converting space-delimited IPv4 address
// to dotted-decimal format
void ipbufferchk(char *IPbuffer)
{
if (NULL == IPbuffer)
{
perror("inet_ntoa");
exit(1);
}
}
// Driver code
int main()
{
char hostbuffer[256];
char *IPbuffer;
struct hostent *host_entry;
int hostname;
hostname = gethostname(hostbuffer, sizeof(hostbuffer));
hostnamechk(hostname);
// To get host information
host_entry = gethostbyname(hostbuffer);
hostentrychk(host_entry);
// Converting Internet network address to ASCII string
IPbuffer = inet_ntoa(*((struct in_addr*)host_entry->h_addr_list[0]));
printf("Host IP: %s", IPbuffer);
return 0;
}
Use of terms used
- The <unistd.h> header defines miscellaneous symbolic constants and types, and declares miscellaneous functions.
- <errno.h> is a header file in the standard library of the C programming language. It defines macros for reporting and retrieving error conditions using the symbol errno.
- The <netdb.h> header shall define the hostent structure
- The <netinet/in. h> header also defines the IN6ADDR_ANY_INIT macro. This macro must be constant at compile time and can be used to initialize a variable of type struct in6_addr to the IPv6 wildcard address. This variable is initialized by the system to contain the loopback IPv6 address.
- <arpa/inet.h> – definitions for internet operations
- The inet_ntoa() function converts the specified Internet host address to a string in the Internet standard dot notation.
- perror is used in C and C++ to print an error message to stderr.
Report Error/ Suggestion