首页 > 解决方案 > golang http server http.ListenAndServe 仅适用于 localhost?

问题描述

我使用 golang 在 Azure Linux VM 中实现了一个 HTTP 服务器。下面是简单的 golang 服务器代码,监听 30175 端口。该端口上没有防火墙。

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))
}

sudo netstat -tlnp 的结果是:

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

我只能在 localhost 中获得响应,但没有来自远程服务器的响应:

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

标签: gotcpserver

解决方案


这与您的代码无关。这是一个典型的防火墙问题。

  • 默认情况下(在 *nix 平台上)所有传入流量都被阻止并允许所有传出。您需要打开操作系统上的端口以允许传入流量到达您的服务器。尝试安装ufw实用程序并运行sudo ufw allow 30175
  • 从问题来看,您的服务器似乎正在使用 tcp6。理想情况下,它不应该引起问题,因为 tcp6 应该同时支持 IPV4 和 IPV6。但如果有意义的话,我建议你将其降级为 tcp。

推荐阅读