diff options
Diffstat (limited to 'src/lib/libc/net/if_indextoname.c')
-rw-r--r-- | src/lib/libc/net/if_indextoname.c | 48 |
1 files changed, 34 insertions, 14 deletions
diff --git a/src/lib/libc/net/if_indextoname.c b/src/lib/libc/net/if_indextoname.c index cca862de61..b05e82e9ff 100644 --- a/src/lib/libc/net/if_indextoname.c +++ b/src/lib/libc/net/if_indextoname.c | |||
@@ -45,29 +45,48 @@ static char __name[IFNAMSIZ]; | |||
45 | char * | 45 | char * |
46 | if_indextoname(unsigned int index, char *name) | 46 | if_indextoname(unsigned int index, char *name) |
47 | { | 47 | { |
48 | int i, fd, len; | 48 | int i, fd = -1, extra, len = 0; |
49 | struct ifconf ifconf; | 49 | struct ifconf ifconf; |
50 | char lastname[IFNAMSIZ], iname[IFNAMSIZ], *retname = NULL; | 50 | char lastname[IFNAMSIZ], iname[IFNAMSIZ], *retname = NULL, *inbuf; |
51 | struct sockaddr *sa; | 51 | struct sockaddr *sa; |
52 | void *p; | 52 | void *p; |
53 | 53 | ||
54 | if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) | 54 | ifconf.ifc_buf = 0; |
55 | return 0; | ||
56 | 55 | ||
57 | if (!name) | 56 | if (!name) |
58 | name = __name; | 57 | name = __name; |
59 | 58 | ||
60 | ifconf.ifc_len = 0; | 59 | if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) |
61 | ifconf.ifc_buf = 0; | ||
62 | if (ioctl(fd, SIOCGIFCONF, (void *) &ifconf)) | ||
63 | goto ret; | ||
64 | if (ifconf.ifc_len < IFNAMSIZ) | ||
65 | goto ret; | ||
66 | if (!(ifconf.ifc_buf = malloc(ifconf.ifc_len))) | ||
67 | goto ret; | ||
68 | if (ioctl(fd, SIOCGIFCONF, (void *) &ifconf)) | ||
69 | goto ret; | 60 | goto ret; |
70 | 61 | ||
62 | /* | ||
63 | * Try ifc_len == 0 hack first, to get the actual length. | ||
64 | * If that fails, revert to a loop which grows the ifc_buf | ||
65 | * until it is sufficiently large. | ||
66 | */ | ||
67 | extra = sizeof(struct ifreq); | ||
68 | while (1) { | ||
69 | ifconf.ifc_len = len; | ||
70 | if (ioctl(fd, SIOCGIFCONF, (void *) &ifconf) == -1 && | ||
71 | ifconf.ifc_buf) | ||
72 | goto ret; | ||
73 | if (ifconf.ifc_buf && | ||
74 | ifconf.ifc_len + extra < len) | ||
75 | break; | ||
76 | if (ifconf.ifc_buf) { | ||
77 | if (len == 0) | ||
78 | len = 4096; | ||
79 | ifconf.ifc_len = len *= 2; | ||
80 | } else { | ||
81 | len = ifconf.ifc_len; | ||
82 | extra = 0; | ||
83 | } | ||
84 | inbuf = realloc(ifconf.ifc_buf, ifconf.ifc_len); | ||
85 | if (inbuf == NULL) | ||
86 | goto ret; | ||
87 | ifconf.ifc_buf = inbuf; | ||
88 | } | ||
89 | |||
71 | i = 0; | 90 | i = 0; |
72 | p = ifconf.ifc_buf; | 91 | p = ifconf.ifc_buf; |
73 | len = ifconf.ifc_len; | 92 | len = ifconf.ifc_len; |
@@ -112,7 +131,8 @@ if_indextoname(unsigned int index, char *name) | |||
112 | retname = name; | 131 | retname = name; |
113 | } | 132 | } |
114 | ret: | 133 | ret: |
115 | close(fd); | 134 | if (fd != -1) |
135 | close(fd); | ||
116 | if (ifconf.ifc_buf) | 136 | if (ifconf.ifc_buf) |
117 | free(ifconf.ifc_buf); | 137 | free(ifconf.ifc_buf); |
118 | return (retname); | 138 | return (retname); |