Replace my C code with tianons Go code

Docker-DCO-1.1-Signed-off-by: Michael Crosby <michael@crosbymichael.com> (github: crosbymichael)
This commit is contained in:
Michael Crosby 2014-02-09 05:54:13 -08:00
parent 971834148c
commit 4f9817a3ca

View file

@ -2,60 +2,6 @@
package netlink package netlink
/*
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <net/if.h>
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 ( import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
@ -696,14 +642,41 @@ done:
return res, nil return res, nil
} }
func NetworkChangeName(oldName, newName string) error { func getIfSocket() (int, error) {
var ( fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, 0)
cold = C.CString(oldName) if err == nil {
cnew = C.CString(newName) return fd, err
)
if errno := int(C.change_name(cold, cnew)); errno != 0 {
return fmt.Errorf("unable to change name %d", errno)
} }
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 return nil
} }