Does anyone know of a way to programmatically obtain my local IP address without having to parse it out.
Enter the interface name as in eth0 on the command line.
Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> 

#define SIOCGIFCONF 0x8912 /* get interface list */ 

int main(int argc, char *argv[])
{ 
	int reqcounts = 10, mysocket, index, findit, count, wefoundit=0;
	struct ifconf ifc; struct ifreq *ifr; struct in_addr *ia; 
	findit= (argc>1);
	if(findit && strlen(argv[1]) > 64)
	{ 
		fprintf(stderr, "Device name too long, can't use it\n");
		findit=0; } 
	mysocket=socket(AF_INET, SOCK_STREAM, 0);
	ifc.ifc_buf = NULL;
	ifc.ifc_len = sizeof(struct ifreq) * reqcounts;
	ifc.ifc_buf = realloc(ifc.ifc_buf, ifc.ifc_len);
	if (ioctl(mysocket, SIOCGIFCONF, &ifc) < 0)
	{ perror("SIOCGIFCONF"); }
	ifr = ifc.ifc_req;
	for (index = 0; index < ifc.ifc_len; index += sizeof(struct ifreq))
	{ 
		ia= (struct in_addr *) ((ifr->ifr_ifru.ifru_addr.sa_data)+2);
		if(findit) count= strcmp(ifr->ifr_ifrn.ifrn_name, argv[1]); 
		if(!findit)
			fprintf(stdout, "%6s %-15s\n", ifr->ifr_ifrn.ifrn_name, inet_ntoa(*ia));
		if (findit && (count==0))
		{ 
			fprintf(stdout, "%s\n", inet_ntoa(*ia));
			wefoundit=1;
		} 
		ifr++;
	} 
	free(ifc.ifc_buf);
	fprintf(stderr, "exiting with %i\n", wefoundit);
return wefoundit;
}