diff --git a/netlink/netlink_linux.go b/netlink/netlink_linux.go index 77ebfcd..46bd3d8 100644 --- a/netlink/netlink_linux.go +++ b/netlink/netlink_linux.go @@ -2,60 +2,6 @@ package netlink -/* -#include -#include -#include -#include - -static int get_socket(void) { - int s_errno; - int fd; - - fd = socket(PF_INET, SOCK_DGRAM, 0); - if (fd >= 0) { - return fd; - } - s_errno = errno; - - fd = socket(PF_PACKET, SOCK_DGRAM, 0); - if (fd >= 0) { - return fd; - } - - fd = socket(PF_INET6, SOCK_DGRAM, 0); - if (fd >= 0) { - return fd; - } - errno = s_errno; - return -1; -} - - -static int change_name(const char *old_name, const char *new_name) { - struct ifreq ifr; - int err; - int fd; - - fd = get_socket(); - if (fd < 0) { - return -1; - } - - strncpy(ifr.ifr_name, old_name, IFNAMSIZ); - strncpy(ifr.ifr_newname, new_name, IFNAMSIZ); - - err = ioctl(fd, SIOCSIFNAME, &ifr); - if (err) { - close(fd); - return -1; - } - close(fd); - return err; -} -*/ -import "C" - import ( "encoding/binary" "fmt" @@ -696,14 +642,41 @@ done: return res, nil } -func NetworkChangeName(oldName, newName string) error { - var ( - cold = C.CString(oldName) - cnew = C.CString(newName) - ) - - if errno := int(C.change_name(cold, cnew)); errno != 0 { - return fmt.Errorf("unable to change name %d", errno) +func getIfSocket() (int, error) { + fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, 0) + if err == nil { + return fd, err } + sErr := err + + fd, err = syscall.Socket(syscall.AF_PACKET, syscall.SOCK_DGRAM, 0) + if err == nil { + return fd, err + } + + fd, err = syscall.Socket(syscall.AF_INET6, syscall.SOCK_DGRAM, 0) + if err == nil { + return fd, err + } + + return -1, sErr +} + +func NetworkChangeName(oldName, newName string) error { + fd, err := getIfSocket() + if err != nil { + return err + } + defer syscall.Close(fd) + IFNAMSIZ := 16 + + data := [32]byte{} + copy(data[:IFNAMSIZ-1], oldName) + copy(data[IFNAMSIZ:IFNAMSIZ*2-1], newName) + + if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), syscall.SIOCSIFNAME, uintptr(unsafe.Pointer(&data[0]))); errno != 0 { + return errno + } + return nil }