Sorry, this is in the wrong blog, but I don't have one for Go/Golang.
Anyway, wanted to do a setsockopt() in Go on a socket I had created. There were a few posts on this, but none that worked too well for me, so here is what I did. Hope others can benefit from it.
Want to thank Rick (Richard Spillane) for his suggestions on introspection in Go.
In my case, I wanted to bind a socket I had created to a particular interface. Here is the code:
func bindToIf(conn net.Conn, interfaceName string) {
Anyway, wanted to do a setsockopt() in Go on a socket I had created. There were a few posts on this, but none that worked too well for me, so here is what I did. Hope others can benefit from it.
Want to thank Rick (Richard Spillane) for his suggestions on introspection in Go.
In my case, I wanted to bind a socket I had created to a particular interface. Here is the code:
func bindToIf(conn net.Conn, interfaceName string) {
ptrVal := reflect.ValueOf(conn)
val := reflect.Indirect(ptrVal)
//next line will get you the net.netFD
fdmember := val.FieldByName("fd")
val1 := reflect.Indirect(fdmember)
netFdPtr := val1.FieldByName("sysfd")
fd := int(netFdPtr.Int())
//fd now has the actual fd for the socket
err := syscall.SetsockoptString(fd, syscall.SOL_SOCKET,
syscall.SO_BINDTODEVICE, interfaceName)
if err != nil {
log.Fatal(err)
}
}
I pulled this code out from some other code, so there might be some formatting errors, but this does work with go 1.2.1 on a Linux machine.
No comments:
Post a Comment