在Unix域套接字上进行安全监听的方法是什么?

huangapple go评论75阅读模式
英文:

Failsafe way of listening on a unix-domain-socket

问题

这段代码在第一次运行时正常工作:

package main

import (
	"context"
	"fmt"
	"net"
)

func main() {
	ctx := context.Background()
	udsName := "dummy.socket"
	var lc net.ListenConfig
	_, err := lc.Listen(ctx, "unix", udsName)
	if err != nil {
		panic(fmt.Sprintf("failed to listen(unix) name %s: %v", udsName, err))
	}
	fmt.Println("all is fine")
}

但在第二次运行时失败:

panic: failed to listen(unix) name dummy.socket: listen unix dummy.socket: bind: address already in use

我可以在Listen()之前删除文件,但如果已经有一个进程在监听此套接字上,这可能会导致失败。

有没有办法检测是否有进程在监听该套接字?

然后,如果旧服务器已经停止运行,我可以删除旧的dummy.socket文件。

英文:

This code works fine on the first run:

package main

import (
	"context"
	"fmt"
	"net"
)


func main() {
	ctx := context.Background()
	udsName := "dummy.socket"
	var lc net.ListenConfig
	_, err := lc.Listen(ctx, "unix", udsName)
	if err != nil {
		panic(fmt.Sprintf("failed to listen(unix) name %s: %v", udsName, err))
	}
	fmt.Println("all is fine")
}

But it fails on the second run:

> panic: failed to listen(unix) name dummy.socket: listen unix dummy.socket: bind: address already in use

I could just remove the file before Listen(), but this could be a failure, if there is already a process listening on this socket.

Is there a way to detect if there is a process listening on the socket?

Then I could remove the old dummy.socket file, if the old server is dead.

答案1

得分: 2

在绑定之前删除Unix套接字文件,这是我知道的唯一“安全”的方法:

package main

import (
    "context"
    "fmt"
    "net"
)


func main() {
    ctx := context.Background()
    udsName := "dummy.socket"
    os.Remove(udsName) //删除Unix套接字文件
    var lc net.ListenConfig
    _, err := lc.Listen(ctx, "unix", udsName)
    if err != nil {
        panic(fmt.Sprintf("无法侦听(unix)名称%s:%v", udsName, err))
    }
    fmt.Println("一切正常")
}
英文:

Delete the unix socket file prior to binding, only 'failsafe' way i know:

package main

import (
    "context"
    "fmt"
    "net"
)


func main() {
    ctx := context.Background()
    udsName := "dummy.socket"
    os.Remove(udsName) //delete the unix socket file
    var lc net.ListenConfig
    _, err := lc.Listen(ctx, "unix", udsName)
    if err != nil {
        panic(fmt.Sprintf("failed to listen(unix) name %s: %v", udsName, err))
    }
    fmt.Println("all is fine")
}

huangapple
  • 本文由 发表于 2023年3月10日 00:02:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687137.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定