diff options
Diffstat (limited to 'src/lib/libc/net/if_nametoindex.c')
| -rw-r--r-- | src/lib/libc/net/if_nametoindex.c | 48 |
1 files changed, 34 insertions, 14 deletions
diff --git a/src/lib/libc/net/if_nametoindex.c b/src/lib/libc/net/if_nametoindex.c index 0318f60680..d41f8ecad1 100644 --- a/src/lib/libc/net/if_nametoindex.c +++ b/src/lib/libc/net/if_nametoindex.c | |||
| @@ -43,27 +43,46 @@ | |||
| 43 | unsigned int | 43 | unsigned int |
| 44 | if_nametoindex(const char *name) | 44 | if_nametoindex(const char *name) |
| 45 | { | 45 | { |
| 46 | int i, fd, len; | 46 | int i, fd = -1, extra, len = 0; |
| 47 | struct ifconf ifconf; | 47 | struct ifconf ifconf; |
| 48 | char lastname[IFNAMSIZ], *thisname; | 48 | char lastname[IFNAMSIZ], *thisname, *inbuf; |
| 49 | unsigned int index = 0; | 49 | unsigned int index = 0; |
| 50 | struct sockaddr *sa; | 50 | struct sockaddr *sa; |
| 51 | void *p; | 51 | void *p; |
| 52 | 52 | ||
| 53 | if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) | ||
| 54 | return 0; | ||
| 55 | |||
| 56 | ifconf.ifc_len = 0; | ||
| 57 | ifconf.ifc_buf = 0; | 53 | ifconf.ifc_buf = 0; |
| 58 | if (ioctl(fd, SIOCGIFCONF, (void *) &ifconf)) | 54 | |
| 59 | goto ret; | 55 | if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) |
| 60 | if (ifconf.ifc_len < IFNAMSIZ) | ||
| 61 | goto ret; | ||
| 62 | if (!(ifconf.ifc_buf = malloc(ifconf.ifc_len))) | ||
| 63 | goto ret; | ||
| 64 | if (ioctl(fd, SIOCGIFCONF, (void *) &ifconf)) | ||
| 65 | goto ret; | 56 | goto ret; |
| 66 | 57 | ||
| 58 | /* | ||
| 59 | * Try ifc_len == 0 hack first, to get the actual length. | ||
| 60 | * If that fails, revert to a loop which grows the ifc_buf | ||
| 61 | * until it is sufficiently large. | ||
| 62 | */ | ||
| 63 | extra = sizeof(struct ifreq); | ||
| 64 | while (1) { | ||
| 65 | ifconf.ifc_len = len; | ||
| 66 | if (ioctl(fd, SIOCGIFCONF, (void *) &ifconf) == -1 && | ||
| 67 | ifconf.ifc_buf) | ||
| 68 | goto ret; | ||
| 69 | if (ifconf.ifc_buf && | ||
| 70 | ifconf.ifc_len + extra < len) | ||
| 71 | break; | ||
| 72 | if (ifconf.ifc_buf) { | ||
| 73 | if (len == 0) | ||
| 74 | len = 4096; | ||
| 75 | ifconf.ifc_len = len *= 2; | ||
| 76 | } else { | ||
| 77 | len = ifconf.ifc_len; | ||
| 78 | extra = 0; | ||
| 79 | } | ||
| 80 | inbuf = realloc(ifconf.ifc_buf, ifconf.ifc_len); | ||
| 81 | if (inbuf == NULL) | ||
| 82 | goto ret; | ||
| 83 | ifconf.ifc_buf = inbuf; | ||
| 84 | } | ||
| 85 | |||
| 67 | i = 0; | 86 | i = 0; |
| 68 | p = ifconf.ifc_buf; | 87 | p = ifconf.ifc_buf; |
| 69 | len = ifconf.ifc_len; | 88 | len = ifconf.ifc_len; |
| @@ -106,7 +125,8 @@ if_nametoindex(const char *name) | |||
| 106 | index = i; | 125 | index = i; |
| 107 | 126 | ||
| 108 | ret: | 127 | ret: |
| 109 | close(fd); | 128 | if (fd != -1) |
| 129 | close(fd); | ||
| 110 | if (ifconf.ifc_buf) | 130 | if (ifconf.ifc_buf) |
| 111 | free(ifconf.ifc_buf); | 131 | free(ifconf.ifc_buf); |
| 112 | return index; | 132 | return index; |
