Checking TCP port in Go?

xuanbao · · 831 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi, I&#39;m trying to write some Go code to check whether a specific TCP port is available at a given address. This is what I&#39;ve come up with so far: </p> <p><a href="https://gist.github.com/ekoecho/c00dbc48b883799e76f7" rel="nofollow">https://gist.github.com/ekoecho/c00dbc48b883799e76f7</a></p> <p>Is this the correct way to do this in Go or is there a more idiomatic approach?</p> <p>Any advice would be much appreciated, thanks!</p> <hr/>**评论:**<br/><br/>james-h: <pre><p>This code is certainly valid and resembles idiomatic Go. With such a short example, it&#39;s hard to get things wrong. But be assured, this looks very reasonable.</p> <p>That being said, the <code>defer conn.Close()</code> could probably just be replaced by <code>conn.Close()</code>. You&#39;re not using <code>conn</code> beyond that point, so you can just close it immediately. </p></pre>Ekoecho: <pre><p>Great, thanks for the quick reply. And thanks for the advice regarding conn.Close vs defer conn.Close(), I hadn&#39;t considered that.</p></pre>xargon7: <pre><p>The note on the gist is correct that this only checks whether something is listening on that port or not, not whether it&#39;s actually available for you to grab.</p> <p>On a related note, the ability to check whether a port is available is <em>generally</em> not useful -- at least, not if you are using that to determine whether to try to grab it. It could happen that the port is taken after you check and before you try to use it.</p> <p>Because of that, generally the pattern is to simply try to bind to the port. If it worked, it was available and now you have it. If not, it was already taken, sorry.</p></pre>Ekoecho: <pre><p>Thanks, you made some interesting points that I was not aware of. In this case I was trying to come up with an efficient way to monitor a port without preventing others from using the service (e.g. check that a web server is available and listening on port 80). I wasn&#39;t sure if this was the best way to go about it but it was the best solution I could come up with on my first attempt. </p></pre>HR-Uriel: <pre><p>Depends what you have in mind. Acting such a way, the counterpart knows that you try. If you do that, all sysadmin will think you are a network scanner, and then they will blacklist automatically your source IP after the second/third time you try to send a SYN , receive the ACK and then close the connection. In theory this works, in practice it can&#39;t go in production. </p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

831 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传