Posted: . At: 3:35 PM. This was 9 years ago. Post ID: 8356
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


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: my-ip --ip eth0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#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);
 
		close(fd);
 
		/* 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.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.