/* $KAME: if_indextoname.c,v 1.7 2000/11/08 03:09:30 itojun Exp $ */12/*-3* SPDX-License-Identifier: BSD-1-Clause4*5* Copyright (c) 1997, 20006* Berkeley Software Design, Inc. All rights reserved.7*8* Redistribution and use in source and binary forms, with or without9* modification, are permitted provided that the following conditions10* are met:11* 1. Redistributions of source code must retain the above copyright12* notice, this list of conditions and the following disclaimer.13*14* THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``AS IS'' AND15* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE16* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE17* ARE DISCLAIMED. IN NO EVENT SHALL Berkeley Software Design, Inc. BE LIABLE18* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL19* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS20* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)21* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT22* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY23* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF24* SUCH DAMAGE.25*26* BSDI Id: if_indextoname.c,v 2.3 2000/04/17 22:38:05 dab Exp27*/2829#include <sys/types.h>30#include <sys/socket.h>31#include <net/if_dl.h>32#include <net/if.h>33#include <ifaddrs.h>34#include <stdlib.h>35#include <string.h>36#include <errno.h>3738/*39* From RFC 2553:40*41* The second function maps an interface index into its corresponding42* name.43*44* #include <net/if.h>45*46* char *if_indextoname(unsigned int ifindex, char *ifname);47*48* The ifname argument must point to a buffer of at least IF_NAMESIZE49* bytes into which the interface name corresponding to the specified50* index is returned. (IF_NAMESIZE is also defined in <net/if.h> and51* its value includes a terminating null byte at the end of the52* interface name.) This pointer is also the return value of the53* function. If there is no interface corresponding to the specified54* index, NULL is returned, and errno is set to ENXIO, if there was a55* system error (such as running out of memory), if_indextoname returns56* NULL and errno would be set to the proper value (e.g., ENOMEM).57*/5859char *60if_indextoname(unsigned int ifindex, char *ifname)61{62struct ifaddrs *ifaddrs, *ifa;63int error = 0;6465if (ifindex == 0) {66errno = ENXIO;67return(NULL);68}6970if (getifaddrs(&ifaddrs) < 0)71return(NULL); /* getifaddrs properly set errno */7273for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {74if (ifa->ifa_addr &&75ifa->ifa_addr->sa_family == AF_LINK &&76ifindex == LLINDEX((struct sockaddr_dl*)ifa->ifa_addr))77break;78}7980if (ifa == NULL) {81error = ENXIO;82ifname = NULL;83}84else85strncpy(ifname, ifa->ifa_name, IFNAMSIZ);8687freeifaddrs(ifaddrs);8889errno = error;90return(ifname);91}929394