Search code examples
gotcpserver

golang http server http.ListenAndServe only works for localhost?


I tied to implement an HTTP server in Azure Linux VM using golang. Below is the simple golang server code, listening on port 30175. And there is no firewall on that port.

package main

import (
    "fmt"
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":30175", nil))
}

The result of sudo netstat -tlnp is:

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:21              0.0.0.0:*               LISTEN      1605/vsftpd     
tcp        0      0 127.0.0.1:3350          0.0.0.0:*               LISTEN      1873/xrdp-sesman
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1697/sshd       
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      1379/cupsd      
tcp        0      0 127.0.0.1:6010          0.0.0.0:*               LISTEN      4879/8          
tcp        0      0 127.0.0.1:6011          0.0.0.0:*               LISTEN      15507/9         
tcp        0      0 0.0.0.0:3389            0.0.0.0:*               LISTEN      1859/xrdp       
tcp        0      0 0.0.0.0:8000            0.0.0.0:*               LISTEN      2112/python     
tcp6       0      0 :::22                   :::*                    LISTEN      1697/sshd       
tcp6       0      0 ::1:631                 :::*                    LISTEN      1379/cupsd      
tcp6       0      0 ::1:6010                :::*                    LISTEN      4879/8          
tcp6       0      0 ::1:6011                :::*                    LISTEN      15507/9         
tcp6       0      0 :::30175                :::*                    LISTEN      46595/HttpHandler

I can get response only in localhost, but no response from remote server:

curl localhost:30175
Hi there, I love !
curl serveripaddress:30175
not working

Solution

  • This is due to Linux listen rules. There is a reject all rule on my rules.

    # listen rules
    sudo iptables -L INPUT --line-numbers
    sudo iptables -D INPUT 8