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

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -