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
+11.9k Golang : Perform sanity checks on filename example
+21.1k Golang : How to get time zone and load different time zone?
+7k Golang : Get Alexa ranking data example
+12.9k Swift : Convert (cast) Int to String ?
+21.5k Golang : GORM create record or insert new record into database example
+9.3k Golang : Convert(cast) string to int64
+11.9k Golang : Detect user location with HTML5 geo-location
+23.4k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+17.3k Golang : Check if IP address is version 4 or 6
+10.1k Golang : Use regular expression to get all upper case or lower case characters example
+19.4k Golang : How to Set or Add Header http.ResponseWriter?
+31.4k Golang : Get local IP and MAC address