Determining one's own IP address.
M Gordon
mfg at castle.ed.ac.uk
Wed Dec 13 00:14:17 AEST 1989
In article <604 at bmers58.UUCP> davem at bmers58.UUCP (Dave Mielke) writes:
>In article <4429 at ur-cc.UUCP> leadley at uhura.cc.rochester.edu (Scott Leadley) writes:
>> Assuming (a lot of things, but primarily that) you wish to do this from
>>the shell command line and that you know the network interface name:
>
>I would like to be able to determine my local IP address without
>involving a hosts file or yp lookup, i.e. from memory, from within a c
>program.
Here's a shortened version of a program I wrote (This bit is very similar to
ifconfig). It prints out the addresses for all a machines interfaces. You
should have no trouble modifying it for what you want.
--------------------------------------------------------------------------------
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <stdio.h>
#define MAX_INTERFACES 10
main(argc,argv)
int argc;
char *argv[];
{
struct ifconf ifc;
struct ifreq *ifreq;
struct sockaddr_in addr;
char ifbuf[MAX_INTERFACES*sizeof(struct ifreq)];
int s,n,i;
s=socket(AF_INET,SOCK_STREAM,0);
ifc.ifc_len=sizeof(ifbuf);
ifc.ifc_buf=ifbuf;
if (ioctl(s,SIOCGIFCONF,&ifc)==-1)
exit(1);
for (n=ifc.ifc_len/sizeof(struct ifreq),ifreq=ifc.ifc_req;n>0;n--,ifreq++)
{
bcopy(ifreq->ifr_addr.sa_data,&addr.sin_port,14);
printf("%s at %-18s ",ifreq->ifr_name,inet_ntoa(addr.sin_addr));
}
}
--------------------------------------------------------------------------------
Michael
--
Michael Gordon - mfg at uk.ac.ed.castle OR mfg at uk.ac.ed.ee
You can't have everything - where would you put it? -- Steven Wright
More information about the Comp.unix.wizards
mailing list