In this tutorial you will learn about the C program to get IP address and its application with practical example.
C program to get IP address
In this tutorial, we will learn to create a C program that will get the IP address of computer using C programming.
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- Array in C Programming.
- Header Libraries and its usage.
Get IP address
In c programming, it is possible to take or fetch the ip address from the computer and convert it into words or can display in words with the help of a very small amount of code. The C language has many types of header libraries which has supported function in them with the help of these files the programming is easy.
1. Create a socket to define network interface IPv4.
2. Define the IPv4 address type.
3. Define the port name where network is attached.
4. Access the network interface information by passing address using ioctl.
5. Extract the IP address.
* C Program For Getting The IP Address
// including the required Header Files
//Declaring the variables
struct ifreq ifr;
char array = "eth0";
no = socket(AF_INET, SOCK_DGRAM, 0);
//From PC Type of address to retrieve - IPv4 IP address
ifr.ifr_addr.sa_family = AF_INET;
//Copying the interface name in the ifreq structure
strncpy(ifr.ifr_name , array , IFNAMSIZ - 1);
ioctl(no, SIOCGIFADDR, &ifr);
printf("IP Address is %s - %s\n" , array , inet_ntoa(( (struct sockaddr_in *)
&ifr.ifr_addr )->sin_addr) );
The above program we have first initialize the required variable.
- no = it will hold the integer value ip.
- ifreq = it will hold the interface name in the ifreq structure.
- ifr = it will hold the address type.
- array = it will hold the integer value for numbers of ip address.
Including the header files required for program
Body of program retrieving the ip address