在Golang中检查服务器的可达性,可以使用`conn.Write`方法。

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

Check for server reachability in Golang conn.Write

问题

我正在开发一个应用程序,尝试将一些数据发送到远程服务器。一旦我获得主机名,我通过使用net.Dialer.DialContext解析主机名来建立连接。一旦解析了主机名,我就继续使用conn.Write方法向连接写入数据。

conn, err := d.DialContext(ctx, string(transport), addr) 
_, err := client.conn.Write([]byte(msg))

遇到的错误:我发现由于某些问题,我无法ping通我的服务器。令人惊讶的是,通过DialContext获得的conn在执行conn.Write时没有报错,并且它继续向同一连接写入数据。

有人可以帮助我修改写入方法,以便在目标服务器不可达时得到错误提示吗?

英文:

I am working on an application that tries to send some data to a remote server. Once I get the hostname, I get a connection by resolving the hostname using net.Dialer.DialContext. Once, I resolve the hostname, I keep on using conn.Write method to write data to the connection.

conn, err := d.DialContext(ctx, string(transport), addr) 
_, err := client.conn.Write([]byte(msg))

Error faced: I observed that due to some issues, I was not able to ping my server. Surprisingly, conn obtained from DialContext did not complain while doing conn.Write and it kept writing to the same connection.

Can someone help me in how to modify my writing methods in order to get an error in case the destination server is not reachable?

答案1

得分: 1

从这个UDP连接示例中:

> 一个“已连接”的UDP套接字可以模拟发送失败的最佳方法是保存ICMP响应,并在下一次写入时将其作为错误返回。

因此,尝试进行第二次conn.Write(用于测试),以确认这次确实会出现错误。

英文:

From this UDP connection example

> the best a "connected" UDP socket can do to simulate a send failure is to save the ICMP response, and return it as an error on the next write.

So try and (for testing) make a second conn.Write, to confirm that you would indeed get an error this time.

huangapple
  • 本文由 发表于 2021年12月6日 13:33:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/70241267.html
匿名

发表评论

匿名网友

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

确定