Sockets 按端口获取服务名称

Sockets 按端口获取服务名称,sockets,go,Sockets,Go,我正在编写简单的网络扫描器,并坚持按端口号解析服务名称。最好的方法是什么?我认为它应该类似于python的socket.getservbyport(),但不幸的是,开发环境基于Windows,而且我想要的是内置解决方案,而不是解析器 package main import ( "fmt" "net" "strings" "sync" "time" ) type PortScanner struct { ip string } func Sca

我正在编写简单的网络扫描器,并坚持按端口号解析服务名称。最好的方法是什么?我认为它应该类似于python的socket.getservbyport(),但不幸的是,开发环境基于Windows,而且我想要的是内置解决方案,而不是解析器

package main

import (
    "fmt"
    "net"
    "strings"
    "sync"
    "time"
)

type PortScanner struct {
    ip string
}

func ScanPort(ip string, port int, timeout time.Duration) {
    target := fmt.Sprintf("%s:%d", ip, port)
    conn, err := net.DialTimeout("tcp", target, timeout)
    if err != nil {
        if strings.Contains(err.Error(), "too many open files") {
            time.Sleep(timeout)
            ScanPort(ip, port, timeout)
        }
        return
    }

    if err = conn.Close(); err != nil {
        fmt.Println(err)
    }
    fmt.Println(port, "open")
}

func (ps *PortScanner) Start(f, l int, timeout time.Duration) {
    wg := sync.WaitGroup{}
    defer wg.Wait()

    for port := f; port <= l; port++ {
        wg.Add(1)
        go func(port int) {
            defer wg.Done()
            ScanPort(ps.ip, port, timeout)
        }(port)
    }
}

func main() {
    ps := &PortScanner{ip: "127.0.0.1"}
    ps.Start(1, 65535, 500*time.Millisecond)
}
主程序包
进口(
“fmt”
“净额”
“字符串”
“同步”
“时间”
)
类型PortScanner结构{
ip字符串
}
func ScanPort(ip字符串、端口int、超时时间、持续时间){
目标:=fmt.Sprintf(“%s:%d”,ip,端口)
conn,err:=net.DialTimeout(“tcp”,目标,超时)
如果错误!=零{
if strings.Contains(err.Error(),“打开的文件太多”){
时间。睡眠(超时)
扫描端口(ip、端口、超时)
}
返回
}
如果err=conn.Close();err!=nil{
fmt.Println(错误)
}
fmt.Println(端口“打开”)
}
func(ps*PortScanner)启动(f,l int,超时时间。持续时间){
wg:=sync.WaitGroup{}
延迟工作组等待()

对于端口:=f;端口您可以修改该netdb库中的代码,以加载您提供的
服务
文件

也许更好,因为这本质上只是一个键/值映射,创建一个
ports.go
文件,其中包含:

var tcpPorts = map[int]string{
    80: "http"
    // ...
}
然后进行常规地图查找

要列出所有TCP端口,可以执行以下操作:

$ sed -E '/tcp$/!d; s!^([a-zA-Z0-9\-]+)\s+([0-9]+)/\w+!\t\2: "\1",!;' /etc/services
1: "tcpmux",
2: "compressnet",
3: "compressnet",
5: "rje",
7: "echo",
9: "discard",
11: "systat",
13: "daytime",
17: "qotd",
19: "chargen",
.. many more ..