[Low level networking] Golang

For some time I wanted to do some low level networking stuff like creating iterative TCP server to handle requests from multiple clients.
The client request’s a file and the TCP server sends the file back. I know i have net package but this is to “high level”. I just wanted to use functions like in C struct sockaddr_in server4_address; , socket(AF_INET, SOCK,STREAM,0) , listen(sd, 25), bind(sock, (struct sockaddr *)&server4_address), sizeof(server4_address)); and add like server4_address.sin_family = AF_INET, server4_address.sin_port = htons(PORT), accept(...) etc…
This is like the C BSD sockets version that i’m very familiar but in golang where to find this low level functions? How is the best way to acces them. I know I have syscall package but golang mantainers said that we should never depend our code to use syscall because the syscall is deprecated in some order.But I saw os packge is depending on some syscall functions. What is the best way to manage/handle this kind of problem?

I guess the best practice is still using net package primarily for compatibility. Second, from what i know golang don’t know packed structs, so , in some circumstances can be very difficult to work with some structs. I would avoid low level…

The net package is certainly not too low level to use for a raw TCP connection. I’ve implemented the binary memcached protocol on top of it and it’s working quite well. Have you tried to implement what you need using the net package already?

Generally the interface will be simpler but you end up doing the same things. Binding to port 25 and listening for connections is as easy as

s, err := net.Listen("tcp", ":25")
if err != nil {
    panic(err) // or something more useful if possible
for {
    conn, err := s.Accept()
    if err != nil {
        // handle error
    // do something with the connection. net.Conn implements io.Reader and io.Writer

You can see the examples and API here: https://golang.org/pkg/net/

But sill is there any way to do network programming avoiding the “net” package all the way?

I didn’t look too deep in this things but looking into net package sources it seems to use syscall for low-level stuff.

Your three options:

  • Use the net package
  • Use the syscall package and heavily test before upgrading
  • Write C

There isn’t a “don’t use net, but use the syscall” package option that promises API stability forever.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.