dongyuandou2521 2014-12-09 02:44
浏览 57

如何在Go中计算已建立的连接?

I'm trying to do basically this in Go:

netstat -an | grep 2375 -c

I need to count the number of connections to the Docker daemon in my regression test for a connection leak bug. However, because I run this in multiple places in different OS (local dev box, CI, etc), I cannot rely on the "netstat" tool, so I wonder how can I do this in a more programmatic way in Go?

I looked around the net package and could not find anything that would help. There are some libraries that basically replace netstat:

https://github.com/drael/GOnetstat https://github.com/dominikh/netstat-nat

But they are not cross-platform compliant (Mac and *nix). Any idea how can I achieve this?

  • 写回答

1条回答 默认 最新

  • douyu4535 2015-02-03 06:07
    关注

    In linux this info is exposed in the /proc filesystem. Use os.Getpid and query the info in /proc/<pid>/fd. Most likely a simple count is good here, if you need more see the proc man page.

    Cross platform compatibility for this kind of thing is going to be roll your own, as the ways of identifying open fd's for a process are very per platform. If you simply need to compile, and pass some tests for this on non linux platforms you can use Go's per platform support to make this a no-op on other platforms, or implement an appropriate solution.

    评论

报告相同问题?

悬赏问题

  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿