Skip to content

Instantly share code, notes, and snippets.

@kostix
Created April 4, 2016 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kostix/2609dc3490a0c02a14b5a7ca799d5983 to your computer and use it in GitHub Desktop.
Save kostix/2609dc3490a0c02a14b5a7ca799d5983 to your computer and use it in GitHub Desktop.
Getting Ethernet interface speed on Linux using Go via cgo
package main
/*
#include <stdio.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <linux/sockios.h>
#include <linux/if.h>
#include <linux/ethtool.h>
#include <string.h>
#include <stdlib.h>
int get_interface_speed(char *ifname){
int sock;
struct ifreq ifr;
struct ethtool_cmd edata;
int rc;
sock = socket(AF_INET, SOCK_STREAM, 0);
// string copy first argument into struct
strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
ifr.ifr_data = &edata;
// set some global options from ethtool API
edata.cmd = ETHTOOL_GSET;
// issue ioctl
rc = ioctl(sock, SIOCETHTOOL, &ifr);
if (rc < 0) {
perror("ioctl"); // lets not error out here
// make sure to zero out speed
return 0;
}
return edata.speed;
}
*/
import "C"
import (
"fmt"
"unsafe"
)
func main() {
ifname := []byte("eth0\x00")
sp := C.get_interface_speed((*C.char)(unsafe.Pointer(&ifname[0])))
fmt.Println(sp)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment