Vitezslav Samel <vitezslav(a)samel.cz> writes:
Horrible, horrible c89 is! Please use only c99/gnu99 standard.
+int iface_get_ifname(int ifindex, char *ifname)
+{
+ int fd;
+ int ir;
+ struct ifreq ifr = {
+ .ifr_ifindex = ifindex
+ };
+ int saved_errno;
+ int cl;
+
+ fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ if (fd == -1)
+ return fd;
+
+ ir = ioctl(fd, SIOCGIFNAME, &ifr);
+
+ /* need to preserve errno across call to close() */
+ saved_errno = errno;
+
+ cl = close(fd);
+
+ /* bug out if ioctl() failed */
+ if (ir != 0) {
+ errno = saved_errno;
+ return ir;
+ }
+
+ /* bug out if close() failed */
+ if (cl != 0)
+ return cl;
+
+ strncpy(ifname, ifr.ifr_name, IFNAMSIZ);
+ return ir;
+}
+
We dont have to check close() here. According man:
"Not checking the return value of *close()* is a common but nevertheless
serious programming error. It is quite possible that errors on a
previous *write(2)* operatio n are first reported at the final *close()*.
Not checking the return value when closing the file may lead to silent
loss of data. This can especially be observed with NFS and with disk
quota."
Thus, when you write, check *close()*, when you read, you don't have
to. Nevertheless we are reading, so don't checking.
If we won't check errno and print some common message, than we don't
have to do the machinery about saving and restoring errno.
I'd suggest shorter version of func like that:
+int dev_ifname(int ifindex, char *ifname)
+{
+ int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ if (fd == -1) // or < 0, I don't care
+ return fd;
+
+ struct ifreq ifr = {
+ .ifr_ifindex = ifindex
+ };
+
+ int ir = ioctl(fd, SIOCGIFNAME, &ifr);
+ close(fd);
+ if (ir)
+ return ir;
+
+ strncpy(ifname, ifr.ifr_name, IFNAMSIZ);
+ return ir;
+}
just for information SIOCGIFNAME cmd returns on error -EFAULT and
-ENODEV, on success 0 is returned.
otherwise patch is good ;)
--
Nikola