Search code examples
clinuxnetwork-programmingip

C Programming: Check if the IP address is added on any given NIC


Problem description: I have a IP address (can be either IPv4/IPv6) and NIC address, how can I check if the IP address is added to the given NIC (or any NIC) using C.

I know it is simple to do the same on command line/using scripts, however I need to check the same in C Program.

Example:
IP - 192.168.0.1
NIC - eth0

Using command line (Linux platform) the below command would tell me if the IP is added or not:

ip addr show | grep "192.168.0.1"

p.s.: Is there any library function which can be used to get similar outputs?


Solution

  • The method(GETIFADDRS) suggested above is correct solution for the stated problem description. The getifaddrs browses through all the IP's on the NIC.

    However in my case there are many IP's addresses added on the NIC/system and I am OK with knowing if the IP is present in any of the NIC. I found a easier/faster solution.

    To check if the IP is added on any of the NIC card of the machine, just open a TCP socket and bind with port=zero(0) and the IP address to be checked. The successful bind will suggest that the IP is available/present.

    Note: This works if IP is added on any of the NIC card in the system. The port zero should be used instead of hard-coding as it selects any available port on in the system (ref. http://compnetworking.about.com/od/tcpip/p/port-numbers-0.htm)

    This method is tested for both IPv4/IPv6 in UNIX environment(rhel)

    PS:Do not forget to close the socket after verifying the presence of IP