Page 1 of 1

Show IP Address for all networking devices *Linux* Rate Topic: -----

#1 no2pencil  Icon User is offline

  • Professor Snuggly Pants
  • member icon

Reputation: 6540
  • View blog
  • Posts: 30,611
  • Joined: 10-May 07

Posted 04 August 2009 - 02:43 AM

This is a quick tutorial that will go over two basic functions for networking :

1.) Discover all network devices on a Linux system
2.) How to use sockets to display the ip address

1st we will need to include some headers.
#include <stdio.h>	// required
#include <stdlib.h>   // 
#include <string.h>  // strcmp
// These all contain network functionality
#include <net/if.h>
#include <sys/ioctl.h>
#include <netinet/in.h>



Now we are going to set up two values. One is our MAX value for arrays, & the 2nd is a trigger to show some debug information.

#define MAX 32
#define DEBUG 1



Now we are ready to jump into main! :)

We are going to accept user input from the command line, so we've included argc & char v arrays. After that we've got some variables. Two are for file input & output, & they are labeled conf & proc. Conf will be out output pointer, while proc is our input pointer. They will be set later when used. Followed next are three integers. Fd is our socket connection, i & k are counter/incriminatory variables. Next we have two structs, each will contain socket information. Then we have a u_char variable, for holding the ip address array. Then we setup our ch character, for handling character input/output, a general buffer, & lastly our double buffer, ENET, which will hold all of the device names. Last but not least are some more integers, DEV for looping through devices, & then flag1 & flag 2 are used for reading the proc file.

int main(int argc,char *argv[]) {
	FILE * conf;
	FILE * proc;
	int fd,i,k;
	struct ifreq ifr;
	u_char *addr;
	char ch,buff[MAX],ENET[4][MAX];
	int DEV=0,flag1=0,flag2=0;



I like to clean the junk out of the array, just to be safe.

	for(DEV=0;DEV<4;DEV++) {
		for(i=0;i<MAX;i++) {
			ENET[DEV][i]='\0';
		}
	}



Now we are going to read the proc file for network devices, & dump the usable output into our conf file. This is done after we determine that we need to loop through them, because no arguments were passed in at execution time. If an argument is given, then there is no need to run through them all.

	DEV=0;
	if(argc<2) {
		printf("Please choose from the following Ethernet devices :\n");
		if(DEBUG==1) printf("Creating configuration file\n");
		conf = fopen("/tmp/air.conf","w+");
		if(!conf) {
			printf("The configuration file failed to open\n");
			exit(0);
		}
		proc = fopen("/proc/net/dev","r");
		if(!proc) {
			printf("Unable to read networking devices\n");
			exit(0);
		}



This is what I consider the most complicated part. I'm sure you'll know of a few ways to perform this in a much easier fashion, but this is how I did it. We read characters while we are not at the end of the file. If that file is a semi-colon, the we only want what's prior, so flag 1 is tripped (but only if flag 2 is tripped, twice, as there are two garbage lines before the devices). If the semi-colon is reached, dump our buffer into the Ethernet array & stuff that into our config file with fprintf. Reset the array, reset the buffer, & lets keep going until we are through all the devices listed in the file.

		if(DEBUG==1) printf("Filling device array\n");
		i=0;
		while(ch!=EOF) {
			ch=fgetc(proc);
			if(ch==':') {
				if(flag2>1) {
					flag1=1;
					sprintf(ENET[DEV],"%s",buff);
					fprintf(conf,"%s",ENET[DEV]);
					DEV++;
				}
			}
			if(ch=='\n') {
				flag2++;
				flag1=0;
				i=0;
				for(k=0;k<MAX;k++) buff[k]='\0';
			}
			if(i<MAX)buff[i]=ch;
			if(flag1==0) {
				if(isalnum(ch))i++; // Strip spaces
			}
		}
		if(conf) fclose(conf);
		if(proc) fclose (proc);
	}



Now, if a device was provided, lets just focus on that device only. We do this by setting DEV to 1 & dumping the given device into our EtherNet device array.

	if(argc==2) {
		sprintf(ENET[0],"%s",argv[1]);
		DEV=1;
	}



With all of our devices discovered, or manually given, lets create a socket, pull the ip address, & display it. If you want to do anything else with it, now would be the time to do so.

	for(i=0;i<DEV;i++) {
		fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_IP);
		memset(&ifr, 0, sizeof(struct ifreq));
		strcpy(ifr.ifr_name, ENET[i]);
		ioctl(fd, SIOCGIFADDR, &ifr);
		addr = (u_char *)&(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr);
		printf("%i of %i %s : addr %d.%d.%d.%d\n",(i+1),DEV,ifr.ifr_name,addr[0],addr[1],addr[2],addr[3]);
		close(fd);
	}
	
	return 0;
}


I hope that you find this tutorial helpful, in either pulling the ethernet devices from proc, or in gathering the ip through sockets.

Last, is the code in it's entirety :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <netinet/in.h>

#define MAX 32
#define DEBUG 1

int main(int argc,char *argv[]) {
	FILE * conf;
	FILE * proc;
	int fd,i,k;
	struct ifreq ifr;
	u_char *addr;
	char ch,buff[MAX],ENET[4][MAX];
	int DEV=0,flag1=0,flag2=0;
	
	/* Empty the array */
	for(DEV=0;DEV<4;DEV++) {
		for(i=0;i<MAX;i++) {
			ENET[DEV][i]='\0';
		}
	}
	DEV=0;
	if(argc<2) {
		printf("Please choose from the following Ethernet devices :\n");
		if(DEBUG==1) printf("Creating configuration file\n");
		conf = fopen("/tmp/air.conf","w+");
		if(!conf) {
			printf("The configuration file failed to open\n");
			exit(0);
		}
		proc = fopen("/proc/net/dev","r");
		if(!proc) {
			printf("Unable to read networking devices\n");
			exit(0);
		}
		if(DEBUG==1) printf("Filling device array\n");
		i=0;
		while(ch!=EOF) {
			ch=fgetc(proc);
			if(ch==':') {
				if(flag2>1) {
					flag1=1;
					sprintf(ENET[DEV],"%s",buff);
					fprintf(conf,"%s",ENET[DEV]);
					DEV++;
				}
			}
			if(ch=='\n') {
				flag2++;
				flag1=0;
				i=0;
				for(k=0;k<MAX;k++) buff[k]='\0';
			}
			if(i<MAX)buff[i]=ch;
			if(flag1==0) {
				if(isalnum(ch))i++; // Strip spaces
			}
		}
		if(conf) fclose(conf);
		if(proc) fclose (proc);
	}

	if(argc==2) {
		sprintf(ENET[0],"%s",argv[1]);
		DEV=1;
	}
	for(i=0;i<DEV;i++) {
		fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_IP);
		memset(&ifr, 0, sizeof(struct ifreq));
		strcpy(ifr.ifr_name, ENET[i]);
		ioctl(fd, SIOCGIFADDR, &ifr);
		addr = (u_char *)&(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr);
		printf("%i of %i %s : addr %d.%d.%d.%d\n",(i+1),DEV,ifr.ifr_name,addr[0],addr[1],addr[2],addr[3]);
		close(fd);
	}
	
	return 0;
}



Is This A Good Question/Topic? 1
  • +

Replies To: Show IP Address for all networking devices

#2 horace  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 768
  • View blog
  • Posts: 3,832
  • Joined: 25-October 06

Posted 13 January 2011 - 11:32 PM

try this which used gethostname() and gethostbyname()
void displayIPaddress(void)
{
      struct hostent *he;
      struct sockaddr_in sin;
      char machine_name[ 300 ];
      // get host computer name
      if (gethostname (machine_name, sizeof (machine_name)))
        {
          perror ("gethostname");
          system("pause"); exit(-1);
        }

     // get host information
     again:
      he = gethostbyname (machine_name);
      if (he == NULL)
        {
          if (errno == TRY_AGAIN)  goto again;
          perror ("gethostbyname");
          system("pause"); exit(-1);
        }

      // extract IP address and display it
      memset(&sin, 0,  sizeof (struct sockaddr_in));
      sin.sin_family = AF_INET;
      sin.sin_port = htons (80);
      memcpy (&sin.sin_addr , he->h_addr_list[ 0 ], he->h_length);
      cout << "Host " << machine_name << " IP address " <<  inet_ntoa (sin.sin_addr) << endl;
    }


if you are using windows you will also need to call WSAStartup()
   #ifdef __WIN32            // windows WINSOCK startup
      WSAData wsaData;
      if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
          return 255;
      }
  #endif


Was This Post Helpful? 1
  • +
  • -

#3 Guest_sarah waleed*


Reputation:

Posted 26 February 2011 - 01:02 AM

please can u make one for windows :)
Was This Post Helpful? 0

#4 horace  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 768
  • View blog
  • Posts: 3,832
  • Joined: 25-October 06

Posted 26 February 2011 - 01:09 AM

View Postsarah waleed, on 26 February 2011 - 08:02 AM, said:

please can u make one for windows :)

the example I gave in my last post will work for windows if you include the WSAStartup

the required header files are
#ifdef __WIN32
  #include <winsock.h>          // for windows
  #define socklen_t int
#else
  #include <arpa/inet.h>        // for UNIX
  #include <netdb.h>
  #define errno h_errno
#endif
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdlib>



Was This Post Helpful? 1
  • +
  • -

#5 sarah waleed  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 124
  • Joined: 12-January 11

Posted 04 March 2011 - 08:25 AM

sorry i think it may be a stupit question but i not found any tutorial that clear it and i have a problem in it
how can i get a result i think i must make a network at lest between two computers but how can i do it
and what is the conditions that must offered in that computers
with regards
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1