$NetBSD: patch-ag,v 1.1 2006/03/30 13:51:29 salo Exp $

--- getifname.c.orig	2004-05-03 10:55:53.000000000 +0200
+++ getifname.c	2005-11-05 21:38:18.000000000 +0100
@@ -45,10 +45,11 @@
 {
 	int fd;
 	struct ifconf	ifc;
-	struct ifreq	ibuf[16],
-			ifr,
+	struct ifreq	ifr,
 			*ifrp,
 			*ifend;
+	char *ibuf;
+	int ibuflen;
 	struct sockaddr_in sa;
 	struct sockaddr_in output_if_addr;
 	int known_output_if = 0;
@@ -72,21 +73,40 @@
 		return -1;
 	}
 
-	memset(ibuf, 0, sizeof(struct ifreq)*16);
-	ifc.ifc_len = sizeof ibuf;
+	ibuf = NULL;
+	ibuflen = 16 * sizeof(struct ifreq);
+	for (;;) {
+		char *nibuf = (char *) realloc(ibuf, ibuflen);
+		if (!nibuf) {
+			perror("[get_if_name] realloc");
+			goto go_out;
+		}
+
+		ibuf = nibuf;
+		memset(ibuf, 0, ibuflen);
+		ifc.ifc_len = ibuflen;
 	ifc.ifc_buf = (caddr_t) ibuf;
 
 	/* gets interfaces list */
 	if ( ioctl(fd, SIOCGIFCONF, (char*)&ifc) == -1 ||
 	     ifc.ifc_len < sizeof(struct ifreq)		) {
 		perror("[get_if_name] ioctl(SIOCGIFCONF)");
-		close(fd);
-		return -1;
+			goto go_out;
+		}
+
+		if (ifc.ifc_len + sizeof(struct ifreq) <= ibuflen)
+			break;
+		if (ibuflen >= 1024 * sizeof(struct ifreq)) {
+			fprintf(stderr, "Warning: Too many network "
+					"interfaces.\n");
+			break;
+		}
+		ibuflen *= 2;
 	}
 
 	/* ifrp points to buffer and ifend points to buffer's end */
-	ifrp = ibuf;
-	ifend = (struct ifreq*) ((char*)ibuf + ifc.ifc_len);
+	ifrp = (struct ifreq *) ibuf;
+	ifend = (struct ifreq *) (ibuf + ifc.ifc_len);
 
 	for (; ifrp < ifend; ifrp++) {
 		strlcpy(ifr.ifr_name, ifrp->ifr_name, sizeof(ifr.ifr_name));
@@ -162,14 +182,15 @@
 			h_if_mtu = ifr.ifr_mtu;
 #endif
 		}
-		close(fd);
-		return 0;
+		goto go_out;
 	}
 	/* interface not found, use 'lo' */
 	strlcpy(ifname, "lo", 1024);
 	strlcpy(ifstraddr, "127.0.0.1", 1024);
 	h_if_mtu = 1500;
 
+go_out:
+	free(ibuf);
 	close(fd);
 	return 0;
 }
