Simple program to return the IP address of an interface.

This program will return the IP address of a specified network interface. Use the –ip parameter to get the IP. For example, this will show the IP address of an ethernet interface: ./a.out –ip eth0.

#include <stdio.h>
#include <string.h> /* for strncpy */
#include <unistd.h> // for close
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
#define BUF 0x05
int main(int argc, char **argv) {
	int fd;
	struct ifreq ifr;
	char* myarg = argv[1];
	char* myarg1 = argv[2];
	if (!myarg || !myarg1) {
		printf("Simple IP information.\n");
		printf("Usage: --ip <IFACE>\n");
	if (argc > 1 && strncmp(argv[1], "--ip", BUF) == 0) {
		fd = socket(AF_INET, SOCK_DGRAM, 0);
		/* I want to get an IPv4 IP address */
		ifr.ifr_addr.sa_family = AF_INET;
		/* I want IP address attached to the specified interface... */
		strncpy(ifr.ifr_name, myarg1, IFNAMSIZ-1);
		ioctl(fd, SIOCGIFADDR, &ifr);
		/* display result */
		fprintf(stdout, "IP information.\n");
		printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
	return 0;

I tested this program on Fedora 22 and it worked perfectly, programming on Linux is easier than programming on Windows with Visual Studio 2012. I hated that. I prefer Linux as you do not need to worry about windows.h or complicated setups for running Windows functions.

No comments have been made. Use this form to start the conversation :)

Leave a Reply