Golang : syscall.Socket example
Just a comparison on how Golang code that utilize net
package looks like if implemented with syscall.Socket
example :
package main
import (
"fmt"
"net"
"os"
)
func main() {
service := "127.0.0.1"
protocol := "icmp"
IPAddr, err := net.ResolveIPAddr("ip4", service)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
IPconn, err := net.ListenIP("ip4:"+protocol, IPAddr)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
buffer := make([]byte, 1024)
for { // display the bytes read from IP connection
num, clientAddr, _ := IPconn.ReadFrom(buffer)
fmt.Println("Reading from : ", clientAddr)
fmt.Printf("% X\n", buffer[:num])
}
}
to
package main
import (
"fmt"
"os"
"syscall"
)
func main() {
fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_ICMP)
if err != nil {
fmt.Println(err)
}
file := os.NewFile(uintptr(fd), "")
for {
buffer := make([]byte, 1024)
num, _ := file.Read(buffer)
fmt.Printf("% X\n", buffer[:num])
}
}
References :
http://www.darkcoding.net/software/raw-sockets-in-go-link-layer/
https://www.socketloop.com/references/golang-net-fileconn-function-example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+10.2k Golang : Meaning of omitempty in struct's field tag
+7k Golang : Of hash table and hash map
+5.7k Golang : Extract unicode string from another unicode string example
+16.7k Golang : Capture stdout of a child process and act according to the result
+14.5k Golang : Find commonalities in two slices or arrays example
+24.7k Golang : Create PDF file from HTML file
+17.8k Golang : Put UTF8 text on OpenCV video capture image frame
+6.9k Golang : Squaring elements in array
+18.4k Golang : Implement getters and setters
+20.8k Golang : Get password from console input without echo or masked
+13.5k Golang : How to determine if a year is leap year?
+13.6k Golang : Human readable time elapsed format such as 5 days ago