Created
April 4, 2016 15:18
-
-
Save kostix/2609dc3490a0c02a14b5a7ca799d5983 to your computer and use it in GitHub Desktop.
Getting Ethernet interface speed on Linux using Go via cgo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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