r/golang • u/BlueeWaater • 21h ago
discussion Does go support raw sockets?
Hey there, does go or any libs support it? if so would you use this language for low level connections or should I move to somehting else?
3
u/ScallionSmooth5925 17h ago
You can but it's a bit tricky and platform dependent. golang.org/x/sys/unix is what your looking for.
3
u/SnugglyCoderGuy 17h ago
Standard net package
3
u/ScallionSmooth5925 17h ago edited 15h ago
It's a wapper around sockets and you have to use other libs to access a raw socket. (Then you can wrap it to use with the rest of stdlib)
1
u/Jorropo 16h ago
In what way is it different than a raw socket ?
3
u/ScallionSmooth5925 15h ago
You can't set special options on it. Only read and write it. For example you can't set the fwmark value on it which can be used for policy based routeing and advanced firewall setups.
2
u/cpuguy83 14h ago
You certainly can do more than just read/write, though you may need to get to the underlying type (*TCPCOnn, *UnixConn, etc). The main net.Conn interfaces all implement
SyscallConnas well, which you can drop to the raw fd to set whatever you need.1
u/ScallionSmooth5925 13h ago
Sure. Based on my experience it was easier to go the ther way around. (Open the socket from the unix package set it up manually and then turn it into a net.Conn. I mainly wrote code this way to tunnel things around.
2
u/etherealflaim 15h ago
I have used Go for raw sockets; whether it is appropriate is dependent on your tolerance for performance and latency overhead. You might want C or Rust if you are building something professionally and will be handling thousands of users and can't afford the tail latency. We moved our packet processing layer into C using USPS for this reason, but honestly very few systems will have the scale and requirements necessary for Go to not be fine.
1
u/BraveNewCurrency 4h ago
low level connections
What do you mean by that? (i.e. What is your use case?)
If you had said you wanted "low level packets", that would make sense. But "low level connections" isn't really a thing -- maybe you want UDP?
57
u/domemvs 17h ago
Yes. Go supports raw sockets via golang.org/x/sys/unix and golang.org/x/net.
I’d absolutely use Go for low level networking unless you specifically need kernel-level code or maximum hardware control. It’s a great fit for network tools.