simplify by using getifaddrs

This commit is contained in:
itojun 2003-09-23 17:57:21 +00:00
parent 7543b55c56
commit ed45a3ba48
1 changed files with 20 additions and 44 deletions

View File

@ -1,5 +1,5 @@
/* $NetBSD: if.c,v 1.15 2003/09/20 13:04:07 itojun Exp $ */ /* $NetBSD: if.c,v 1.16 2003/09/23 17:57:21 itojun Exp $ */
/* $KAME: if.c,v 1.21 2002/05/21 14:26:55 itojun Exp $ */ /* $KAME: if.c,v 1.31 2003/09/23 10:58:20 itojun Exp $ */
/* /*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
@ -85,53 +85,29 @@ get_rtaddrs(int addrs, struct sockaddr *sa, struct sockaddr **rti_info)
struct sockaddr_dl * struct sockaddr_dl *
if_nametosdl(char *name) if_nametosdl(char *name)
{ {
int mib[6] = {CTL_NET, AF_ROUTE, 0, 0, NET_RT_IFLIST, 0}; struct ifaddrs *ifap, *ifa;
char *buf, *next, *lim; struct sockaddr_dl *sdl = NULL;
size_t len;
struct if_msghdr *ifm;
struct sockaddr *sa, *rti_info[RTAX_MAX];
struct sockaddr_dl *sdl = NULL, *ret_sdl = NULL;
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) if (getifaddrs(&ifap) != 0)
return (NULL); return (NULL);
if ((buf = malloc(len)) == NULL)
return (NULL);
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0)
goto end;
lim = buf + len; for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
for (next = buf; next < lim; next += ifm->ifm_msglen) { if (strcmp(ifa->ifa_name, name) != 0)
ifm = (struct if_msghdr *)next; continue;
if (ifm->ifm_type == RTM_IFINFO) { if (ifa->ifa_addr->sa_family != AF_LINK)
sa = (struct sockaddr *)(ifm + 1); continue;
get_rtaddrs(ifm->ifm_addrs, sa, rti_info);
if ((sa = rti_info[RTAX_IFP]) != NULL) { sdl = malloc(ifa->ifa_addr->sa_len);
if (sa->sa_family == AF_LINK) { if (!sdl)
sdl = (struct sockaddr_dl *)sa; continue; /*XXX*/
if (strlen(name) != sdl->sdl_nlen)
continue; /* not same len */ memcpy(sdl, ifa->ifa_addr, ifa->ifa_addr->sa_len);
if (strncmp(&sdl->sdl_data[0], freeifaddrs(ifap);
name, return (sdl);
sdl->sdl_nlen) == 0) {
break;
}
}
}
}
}
if (next == lim) {
/* search failed */
goto end;
} }
if ((ret_sdl = malloc(sdl->sdl_len)) == NULL) freeifaddrs(ifap);
goto end; return (NULL);
memcpy((caddr_t)ret_sdl, (caddr_t)sdl, sdl->sdl_len);
return (ret_sdl);
end:
free(buf);
return (ret_sdl);
} }
int int