shell - How to find the ports that is being used by a process in golang or in general? -
my binary takes port parameter , starts http server. if pass 0 -port, find free port , start on it.
after this, how find port if have command object me , can process id? trying write application in golang. curious how done in general.
it's os specific, on linux can
netstat -npl
that list programs listening on ports
if want print out app, can use alternative form of starting http server creating own tcp listener , call http.serve
example:
package main import ( "fmt" "net" "net/http" "os" ) func main() { lsnr, err := net.listen("tcp", ":0") if err != nil { fmt.println("error listening:", err) os.exit(1) } fmt.println("listening on:", lsnr.addr()) err = http.serve(lsnr, nil) fmt.println("server exited with:", err) os.exit(1) }
outputs:
listening on: [::]:53939
Comments
Post a Comment