如何将Golang服务器监听器设置为仅适用于我的局域网网络?

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

How to set the golang server listener available for only my LAN network

问题

我正在使用iris平台进行Go语言编程(我是一个初学者)。我想让我家中的所有计算机都能够访问作为本地机器之一的Go服务器。当我将监听器设置为我的网络IP(192.168.0.0)或任何指定的IP(192.168.0.15)时,它会返回一个恐慌错误。只有可用的0.0.0.0或127.0.0.1/localhost或192.168.0.19 - 这与localhost相同。

错误信息是:panic: listen tcp4 192.168.0.12:9999: bind: The requested address is not valid in its context.

谢谢大家的帮助。

英文:

I am using iris platform to do programming in go language (I am very beginner). I want to make all my computers at home be available for accessing to go server which is one of the local machine as well. When I set the listener with my network IP (192.168.0.0) or with any specified IP (192.168.0.15) it gives me panic error back. Only available 0.0.0.0 or 127.0.0.1/localhost or 192.168.0.19 - that is same as localhost

import "net"

...

ln, err := net.Listen("tcp4", "192.168.12:9999")
    if err != nil{
	    panic(err)
    }

    iris.Serve(ln)

...

The error is: panic: listen tcp4 192.168.0.12:9999: bind: The requested address is not valid in its context.

Thanks to all for help.

答案1

得分: 7

你应该了解一下网络工作原理,但以下是一些入门要点。

你监听的是一个端口,而不是一个IP地址。所以,无论你使用哪台机器作为服务器,都要找到你的本地IP地址:

在Linux或Mac上,你可以通过多种方式获取:

使用ifconfig | grep netmask命令,获取你的本地地址,例如192.168.x.xx

然后,使用你的Go程序启动服务器,并在本地端口(如8080)上进行监听。

例如:

if err := http.ListenAndServe(":8080", nil); err != nil {
    //处理错误
}

然后,你可以使用同一Wi-Fi网络下的其他设备访问该服务器。使用另一台计算机,在浏览器中访问192.168.x.xx:8080

回答你在评论中的问题,除非他们与你的Wi-Fi网络连接,否则外部人员无法访问你的本地服务器。

英文:

You should read up on how networking works but here are some points to get you started.

You listen on a port, not an IP address. So whatever machine you're using as your server, find your local IP address:

On Linux or Mac you can do it many ways:

ifconfig | grep netmask and get your local address eg. 192.168.x.xx

Then start up your server with your Go program and listen on a localhost port like 8080.

eg.

if err := http.ListenAndServe(":8080", nil); err != nil {
    //handle error
}

Then you can access the server with other machines in your house assuming they are on the same Wifi. Use a different computer and visit 192.168.x.xx:8080 from a browser.

To answer your question in your comments, outsiders cannot access your local server unless they have a connection to your Wifi.

huangapple
  • 本文由 发表于 2016年11月20日 03:39:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/40697131.html
匿名

发表评论

匿名网友

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

确定