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.
Prerequisites
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.
Algorithm:-
1 2 3 4 5 |
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. |
Program:-
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 |
/* * C Program For Getting The IP Address */ // including the required Header Files #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <net/if.h> #include <unistd.h> #include <arpa/inet.h> int main() { //Declaring the variables int no; 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); close(no); //display result printf("IP Address is %s - %s\n" , array , inet_ntoa(( (struct sockaddr_in *) &ifr.ifr_addr )->sin_addr) ); return 0; } |
Output:-
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
Main Program