/* $KAME: if_nametoindex.c,v 1.6 2000/11/24 08:18:54 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_nametoindex.c,v 2.3 2000/04/17 22:38:05 dab Exp27*/2829#include "namespace.h"30#include <sys/types.h>31#include <sys/socket.h>32#include <sys/sockio.h>33#include <net/if.h>34#include <net/if_dl.h>35#include <ifaddrs.h>36#include <stdlib.h>37#include <string.h>38#include <errno.h>39#include <unistd.h>40#include "un-namespace.h"4142/*43* From RFC 2553:44*45* 4.1 Name-to-Index46*47*48* The first function maps an interface name into its corresponding49* index.50*51* #include <net/if.h>52*53* unsigned int if_nametoindex(const char *ifname);54*55* If the specified interface name does not exist, the return value is56* 0, and errno is set to ENXIO. If there was a system error (such as57* running out of memory), the return value is 0 and errno is set to the58* proper value (e.g., ENOMEM).59*/6061unsigned int62if_nametoindex(const char *ifname)63{64int s;65struct ifreq ifr;66struct ifaddrs *ifaddrs, *ifa;67unsigned int ni;6869s = _socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);70if (s != -1) {71memset(&ifr, 0, sizeof(ifr));72strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));73if (_ioctl(s, SIOCGIFINDEX, &ifr) != -1) {74_close(s);75return (ifr.ifr_index);76}77_close(s);78}7980if (getifaddrs(&ifaddrs) < 0)81return(0);8283ni = 0;8485for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {86if (ifa->ifa_addr &&87ifa->ifa_addr->sa_family == AF_LINK &&88strcmp(ifa->ifa_name, ifname) == 0) {89ni = LLINDEX((struct sockaddr_dl*)ifa->ifa_addr);90break;91}92}9394freeifaddrs(ifaddrs);95if (!ni)96errno = ENXIO;97return(ni);98}99100101