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
+3.9k Linux : How to set root password in Linux Mint
+15.7k Golang : Get input from keyboard
+16.5k Golang : Read data from config file and assign to variables
+6.1k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+7.9k Golang : Heap sort example
+6.8k Gogland : Where to put source code files in package directory for rookie
+23k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+6.8k Golang : Error reading timestamp with GORM or SQL driver
+4.7k Golang : Get S3 or CloudFront object or file information
+30.7k Golang : Validate email address with regular expression
+19.6k Golang : Clean up null characters from input data
+10.4k Golang : Display a text file line by line with line number example