Get your current IP address by C

This article will help you to write a program to get IP address of your system. We can get our IP address in several way. You may have known another way to print IP address. Let’s see some C program to get IP address.

C program to get IP address

This is the simplest way to get your IP address if you are using windows operating system. Let’s go to the code.

// code here

Output of this get IP address program:

ip-address-program-in-c-get-ip-address-in-c

This will print your own IP address. Let’s see another C program which can only be used in Linux operating system to print IP address.

#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(){
  int num;
  struct ifreq ifr;
  char array[] = "eth0";

  num = socket(AF_INET, SOCK_DGRAM, 0);

  ifr.ifr_addr.sa_family = AF_INET;

  strncpy(ifr.ifr_name , array , IFNAMSIZ - 1);
  ioctl(num, SIOCGIFADDR, &ifr);
  close(num);

  printf("\nYour IP Address is %s - %s\n" , array , inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr) );
  
  return 0;
}

Previous pagePrint date and time

Next page:  Shutdown computer by C