2000-11-03 18:37:53

by Chris Friesen

[permalink] [raw]
Subject: how to get IP address of current machine from C++ code?

I would like to get the IP address of one of the interfaces of the
machine that I'm currently on from within some C++ code. It looks like
I should be able to do this by doing an

ioctl(atoi(fd, SIOCGIFADDR, &ifr)

with the interface name set in the appropriate field in ifr, but I'm not
sure how I should be getting the proper value for fd. I would
appreciate some help on this, or if there is a better way then I'd love
to hear it.



Chris Friesen | MailStop: 043/33/F10
Nortel Networks | work: (613) 765-0557
3500 Carling Avenue | fax: (613) 765-2986
Nepean, ON K2H 8E9 Canada | email: [email protected]

2000-11-03 21:10:05

by David Ford

[permalink] [raw]
Subject: Re: how to get IP address of current machine from C++ code?

* short hack to grab interface information
* gcc -o gi gi.c; strip gi
* Blu3, Jan 1999

#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 iface list */

int main(int argc, char *argv[])
int numreqs = 30, sd, n, search, tick, found=0;
struct ifconf ifc;
struct ifreq *ifr;
struct in_addr *ia;

// if there is an arg on the command line, print out the ip of that device
// only. note the numreqs in the above, modify that as is desired.

search= (argc>1);
if(search && strlen(argv[1]) > 64) {
fprintf(stderr, "specified device name too large, ignoring\n");

sd=socket(AF_INET, SOCK_STREAM, 0);
ifc.ifc_buf = NULL;
ifc.ifc_len = sizeof(struct ifreq) * numreqs;
ifc.ifc_buf = realloc(ifc.ifc_buf, ifc.ifc_len);
if (ioctl(sd, SIOCGIFCONF, &ifc) < 0) {

ifr = ifc.ifc_req;
for (n = 0; n < ifc.ifc_len; n += sizeof(struct ifreq)) {
ia= (struct in_addr *) ((ifr->ifr_ifru.ifru_addr.sa_data)+2);
tick= strcmp(ifr->ifr_ifrn.ifrn_name, argv[1]);

fprintf(stdout, "%6s %-15s\n", ifr->ifr_ifrn.ifrn_name, inet_ntoa(*ia));

if (search && (tick==0)) {
fprintf(stdout, "%s\n", inet_ntoa(*ia));

fprintf(stderr, "exiting with %i\n", found);

gi.c (1.46 kB)
david.vcf (239.00 B)
Card for David Ford
Download all attachments