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
+27k Golang : Find files by name - cross platform example
+9.8k Golang : Sort and reverse sort a slice of integers
+15.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+13.8k Golang : convert rune to unicode hexadecimal value and back to rune character
+5.2k Golang : Get FX sentiment from website example
+15.2k Golang : Delete certain files in a directory
+4.8k Google : Block or disable caching of your website content
+9.3k Golang : Get all countries currencies code in JSON format
+20k Golang : Count number of digits from given integer value
+7.3k Golang : Scanf function weird error in Windows
+16.1k Golang : How to extract links from web page ?