[Vm-dev] Finding ip address for eth0?
Ian Piumarta
piumarta at speakeasy.net
Wed Aug 26 23:10:30 UTC 2009
On Aug 26, 2009, at 3:15 PM, Andreas Raab wrote:
> David T. Lewis wrote:
>> #!/bin/sh
>
> Wow, without sed? I'm impressed ;-) And you know what, that's just
> what I'll do. Thanks for the snippet.
If you change your mind, your primitive could evolve trivially from
the following.
On Darwin this picks up inet4 and inet6 interface addresses.
SIOCGIFCONF seems to be broken on Linux and it only picks up inet4
addresses regardless of the address family of the socket.
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#ifndef s6_addr16
# define s6_addr16 __u6_addr.__u6_addr16
#endif
int main(int argc, char **argv)
{
struct ifreq *ifr;
struct ifconf ifc;
char buf[32768];
int s= socket(AF_INET, SOCK_DGRAM, 0);
if (-1 == s) return -1;
ifc.ifc_len= sizeof(buf);
ifc.ifc_buf= buf;
if (ioctl(s, SIOCGIFCONF, &ifc) < 0) {
perror("SIOCGIFCONF");
goto die;
}
for (ifr= ifc.ifc_req; (char *)ifr < (char *)ifc.ifc_req +
ifc.ifc_len;) {
switch (ifr->ifr_addr.sa_family) {
case AF_INET: {
struct sockaddr_in *sin= (struct sockaddr_in *)&ifr->ifr_addr;
printf("%s\t%s\n", ifr->ifr_name,
inet_ntoa(sin->sin_addr));
break;
}
case AF_INET6: {
struct sockaddr_in6 *sin6= (struct sockaddr_in6 *)&ifr->ifr_addr;
struct in6_addr *in6= &sin6->sin6_addr;
printf("%s\t%x:%x:%x:%x:%x:%x:%x:%x\n", ifr->ifr_name,
in6->s6_addr16[0], in6->s6_addr16[1], in6->s6_addr16[2], in6-
>s6_addr16[3],
in6->s6_addr16[4], in6->s6_addr16[5], in6->s6_addr16[6], in6-
>s6_addr16[7]);
break;
}
default:
break;
}
# if defined(linux)
++ifr;
# else
ifr= (struct ifreq *)((char *)ifr + sizeof(ifr->ifr_name) + ifr-
>ifr_addr.sa_len);
# endif
}
die:
close(s);
return 0;
}
More information about the Vm-dev
mailing list