How to find IP Address of Computer program in C

How to find IP Address of Computer program in C : Network Programming

What is IP Address of a computer?

  • The IP address is the logical address given to a computer which is connected to a network.
  • It is also known as IPv4 (version 4) address.
  • It is of 32 bit in length. These IP addresses are unique and universal.
  • It can be denoted either in binary notation or dotted decimal notation.

In this post lets see how to find ip address of a computer program in C.


Binary Notation 01110101    10010101   00011101   00000010
Dotted Decimal Notation

As I said earlier, each system has a specific IP address while connected to a network. Now we will see how to find IP address on computer using C Program.

C Program To find IP address Of a Computer:

How to find IP Address of Computer program Explanation:

Hope you find a lot of new terms in the above coding…..
Don’t get too confused. Read the following to understand the above program.

  • In the above program, we include a lot library files.

  • Here we create a structure ( struct ifreq ifr), for passing data in and out of ioctl.
  • Create an array to store and display IP address array[]= “eth0”. The array points to a null-terminated string containing the name of the interface (for example, eth0).
  • Then create a datagram socket, socket(AF_INET, SOCK_DGRAM, 0). It is open socket descriptor with the address family AF_INET.
  • Now Type of address to  be retrieved is specified – Here it is  IP (IPv4) address as follows.

  • Then copy the interface name into the structure using the function, strncpy().
  • While copying, the ifreq structure should initially contain the name of the interface to be queried, which should be copied into the ifr.ifr_name field.

  • Here, ioctl calls a file descriptor to act on. In the case of SIOCGIFADDR this must refer to a socket (for example, a regular file) and must be of the address family that you wish to obtain (AF_INET in this instance).Then close the socket.
  • If this operation completes  then the hardware address of the interface have been returned in ifr.ifr_addr in the form of a struct sockaddr_in.
  • Finally to display the IP address, we have to do the following steps:
  1. Place the returned IP address  to a struct sockaddr_in.
  2. Extract the sin_addr field of this structure to obtain a struct in_addr.
  3. Extract the s_addr field of the in_addr structure to obtain an in_addr_t .
  4. Finally, convert the s_addr field (which is in network byte order) into whatever representation you require and display it.

All these four steps are done in a single line of code:

Hope you understand the working of the program…. Try in your own system in network…

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *