C Program to Display the IP Address of the System

C Program to Display the IP Address of the System.

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <sys/types.h>
  4. #include <sys/socket.h>
  5. #include <sys/ioctl.h>
  6. #include <netinet/in.h>
  7. #include <net/if.h>
  8. #include <unistd.h>
  9. #include <arpa/inet.h>
  10.  
  11. int main()
  12. {
  13.     int n;
  14.     struct ifreq ifr;
  15.     char array[] = "eth0";
  16.  
  17.     n = socket(AF_INET, SOCK_DGRAM, 0);
  18.     //Type of address to retrieve - IPv4 IP address
  19.     ifr.ifr_addr.sa_family = AF_INET;
  20.     //Copy the interface name in the ifreq structure
  21.     strncpy(ifr.ifr_name , array , IFNAMSIZ - 1);
  22.     ioctl(n, SIOCGIFADDR, &ifr);
  23.     close(n);
  24.     //display result
  25.     printf("IP Address is %s - %s\n" , array , inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr) );
  26.     return 0;
  27. }

 

Comments

Popular posts from this blog

C Program to Display the ATM Transaction

Java programming language

Python Program to Print all Prime Numbers in an Interval