Skip to content

Instantly share code, notes, and snippets.

@mangalaman93
Last active May 14, 2024 02:39
Show Gist options
  • Save mangalaman93/eba276775541756694ee to your computer and use it in GitHub Desktop.
Save mangalaman93/eba276775541756694ee to your computer and use it in GitHub Desktop.
setting low level socket options in golang (SO_PRIORITY, SO_REUSEADDR)
package main
import (
"bufio"
"fmt"
"net"
"os"
"syscall"
)
const (
PRIORITY = 2
PORT = "6000"
)
func main() {
ln, err := net.Listen("tcp", "127.0.0.1:"+PORT)
if err != nil {
fmt.Println("error in listening on socket:", err)
os.Exit(1)
}
fmt.Println("listening on socket!")
con, err := ln.Accept()
if err != nil {
fmt.Println("unable to accept connection on socket:", err)
os.Exit(1)
}
fmt.Println("accepted connection from:", con.RemoteAddr())
defer con.Close()
tcpconn, ok := con.(*net.TCPConn)
if !ok {
fmt.Println("error in casting *net.Conn to *net.TCPConn!")
os.Exit(1)
}
file, err := tcpconn.File()
if err != nil {
fmt.Println("error in getting file for the connection!")
os.Exit(1)
}
err = syscall.SetsockoptInt(int(file.Fd()), syscall.SOL_SOCKET, syscall.SO_PRIORITY, PRIORITY)
file.Close()
if err != nil {
fmt.Println("error in setting priority option on socket:", err)
os.Exit(1)
}
message, _ := bufio.NewReader(con).ReadString('\n')
fmt.Print("Message Received: ", string(message))
fmt.Fprintf(con, "Hello World!\n")
}
@QuinnCiccoretti
Copy link

QuinnCiccoretti commented Dec 14, 2022

I don't think this will work. As described in this article sock opts must be set before the call to Listen(). I honestly have no idea how this is working given you seem to close the socket's file as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment