golang学习笔记——TCP端口扫描器

2023-12-08 07:20

本文主要是介绍golang学习笔记——TCP端口扫描器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • TCP 端口扫描器
    • 非并发版本
    • 并发版本
    • goroutine 池并发版 TCP 端口扫描器
  • time.Since
    • func Since
  • net包Conn 接口
    • func Dial
    • func DialTimeout
    • func FileConn

TCP 端口扫描器

非并发版本

package mainimport ("fmt""net"
)func main() {for i := 21; i < 120; i++ {address := fmt.Sprintf("192.168.1.1:%d", j)conn, err := net.Dial("tcp", address)if err != nil {fmt.Printf("%s关闭了\n", address)continue}conn.Close()fmt.Printf("%s 打开了!!!\n", address)}
}

并发版本

package mainimport ("fmt""net""sync""time"
)func main() {start := time.Now()var wg sync.WaitGroupfor i := 21; i < 120; i++ {wg.Add(1)go func(j int) {defer wg.Done()address := fmt.Sprintf("192.168.1.1:%d", j)conn, err := net.Dial("tcp", address)if err != nil {//fmt.Printf("%s关闭了\n", address)return}conn.Close()fmt.Printf("%s 打开了!!!\n", address)}(i)}wg.Wait()elapsed := time.Since(start) / 1e9fmt.Printf("/n/n%d seconds", elapsed)
}

goroutine 池并发版 TCP 端口扫描器

在这里插入图片描述

创建固定数量的mgoroutine(代码中创建了500个),利用channel的机制,往channel中传递n个数据,然后分配给这mgoroutinem<=n。对带缓存的channel不理解的可以看一下通道缓冲区 。

package mainimport ("fmt""net""sort""time"
)func worker(ports chan int, results chan int) {for p := range ports {address := fmt.Sprintf("192.168.10.11:%d", p)conn, err := net.Dial("tcp", address)//失败if err != nil {results <- 0continue}conn.Close()//成功results <- p}
}func main() {start := time.Now()ports := make(chan int, 100)results := make(chan int)//采用slice类型保存结果var openports []intvar closeports []int//创建500个goroutinefor i := 0; i < 500; i++ {go worker(ports, results)}//发送任务 需要单独的goroutinego func() {for i := 1; i < 65535; i++ {ports <- i}}()//接收结果 在主goroutine中完成for i := 1; i < 65535; i++ {port := <-resultsif port != 0 {openports = append(openports, port)} else {closeports = append(closeports, port)}}close(ports)close(results)sort.Ints(openports)sort.Ints(closeports)for _, port := range openports {fmt.Printf("%d open\n", port)}//for _, port := range closeports {//	fmt.Printf("%d closed\n", port)//}elapsed := time.Since(start) / 1e9fmt.Printf("\n\n%d seconds", elapsed)
}

运行

$ go build && m
25 open
.
.
.
902 open
912 open22 seconds

测试中发现,把500个goroutine改为20000个,速度是变快了,但结果并不准确。

time.Since

func Since

func Since(t Time) Duration

Since returns the time elapsed since t. It is shorthand for time.Now().Sub(t).

Since返回自t以来经过的时间。它是时间的简写。Now().Sub(t).

net包Conn 接口

type Conn interface {// Read reads data from the connection.// Read can be made to time out and return an error after a fixed// time limit; see SetDeadline and SetReadDeadline.Read(b []byte) (n int, err error)// Write writes data to the connection.// Write can be made to time out and return an error after a fixed// time limit; see SetDeadline and SetWriteDeadline.Write(b []byte) (n int, err error)// Close closes the connection.// Any blocked Read or Write operations will be unblocked and return errors.Close() error// LocalAddr returns the local network address, if known.LocalAddr() Addr// RemoteAddr returns the remote network address, if known.RemoteAddr() Addr// SetDeadline sets the read and write deadlines associated// with the connection. It is equivalent to calling both// SetReadDeadline and SetWriteDeadline.//// A deadline is an absolute time after which I/O operations// fail instead of blocking. The deadline applies to all future// and pending I/O, not just the immediately following call to// Read or Write. After a deadline has been exceeded, the// connection can be refreshed by setting a deadline in the future.//// If the deadline is exceeded a call to Read or Write or to other// I/O methods will return an error that wraps os.ErrDeadlineExceeded.// This can be tested using errors.Is(err, os.ErrDeadlineExceeded).// The error's Timeout method will return true, but note that there// are other possible errors for which the Timeout method will// return true even if the deadline has not been exceeded.//// An idle timeout can be implemented by repeatedly extending// the deadline after successful Read or Write calls.//// A zero value for t means I/O operations will not time out.SetDeadline(t time.Time) error// SetReadDeadline sets the deadline for future Read calls// and any currently-blocked Read call.// A zero value for t means Read will not time out.SetReadDeadline(t time.Time) error// SetWriteDeadline sets the deadline for future Write calls// and any currently-blocked Write call.// Even if write times out, it may return n > 0, indicating that// some of the data was successfully written.// A zero value for t means Write will not time out.SetWriteDeadline(t time.Time) error
}

Conn is a generic stream-oriented network connection.
Conn是一种通用的面向流的网络连接。

Multiple goroutines may invoke methods on a Conn simultaneously.
多个goroutine可以同时调用一个Conn上的方法。

func Dial

func Dial(network, address string) (Conn, error)

Dial connects to the address on the named network.
拨号连接到命名网络上的地址。

Known networks are “tcp”, “tcp4” (IPv4-only), “tcp6” (IPv6-only), “udp”, “udp4” (IPv4-only), “udp6” (IPv6-only), “ip”, “ip4” (IPv4-only), “ip6” (IPv6-only), “unix”, “unixgram” and “unixpacket”.

For TCP and UDP networks, the address has the form “host:port”. The host must be a literal IP address, or a host name that can be resolved to IP addresses. The port must be a literal port number or a service name. If the host is a literal IPv6 address it must be enclosed in square brackets, as in “[2001:db8::1]:80” or “[fe80::1%zone]:80”. The zone specifies the scope of the literal IPv6 address as defined in RFC 4007. The functions JoinHostPort and SplitHostPort manipulate a pair of host and port in this form. When using TCP, and the host resolves to multiple IP addresses, Dial will try each IP address in order until one succeeds.

Examples:

Dial("tcp", "golang.org:http")
Dial("tcp", "192.0.2.1:http")
Dial("tcp", "198.51.100.1:80")
Dial("udp", "[2001:db8::1]:domain")
Dial("udp", "[fe80::1%lo0]:53")
Dial("tcp", ":80")

For IP networks, the network must be “ip”, “ip4” or “ip6” followed by a colon and a literal protocol number or a protocol name, and the address has the form “host”. The host must be a literal IP address or a literal IPv6 address with zone. It depends on each operating system how the operating system behaves with a non-well known protocol number such as “0” or “255”.

Examples:

Dial("ip4:1", "192.0.2.1")
Dial("ip6:ipv6-icmp", "2001:db8::1")
Dial("ip6:58", "fe80::1%lo0")

For TCP, UDP and IP networks, if the host is empty or a literal unspecified IP address, as in “:80”, “0.0.0.0:80” or “[::]:80” for TCP and UDP, “”, “0.0.0.0” or “::” for IP, the local system is assumed.

For Unix networks, the address must be a file system path.

func DialTimeout

func DialTimeout(network, address string, timeout time.Duration) (Conn, error)

DialTimeout acts like Dial but takes a timeout.
DialTimeout的作用类似于Dial,但需要超时。

The timeout includes name resolution, if required. When using TCP, and the host in the address parameter resolves to multiple IP addresses, the timeout is spread over each consecutive dial, such that each is given an appropriate fraction of the time to connect.

See func Dial for a description of the network and address parameters.

func FileConn

func FileConn(f *os.File) (c Conn, err error)

FileConn returns a copy of the network connection corresponding to the open file f. It is the caller’s responsibility to close f when finished. Closing c does not affect f, and closing f does not affect c.
FileConn返回与打开的文件f相对应的网络连接的副本。完成后关闭f是调用者的责任。关闭c不影响f,关闭f不影响c。

这篇关于golang学习笔记——TCP端口扫描器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/469006

相关文章

Golang操作DuckDB实战案例分享

《Golang操作DuckDB实战案例分享》DuckDB是一个嵌入式SQL数据库引擎,它与众所周知的SQLite非常相似,但它是为olap风格的工作负载设计的,DuckDB支持各种数据类型和SQL特性... 目录DuckDB的主要优点环境准备初始化表和数据查询单行或多行错误处理和事务完整代码最后总结Duck

Golang的CSP模型简介(最新推荐)

《Golang的CSP模型简介(最新推荐)》Golang采用了CSP(CommunicatingSequentialProcesses,通信顺序进程)并发模型,通过goroutine和channe... 目录前言一、介绍1. 什么是 CSP 模型2. Goroutine3. Channel4. Channe

Golang使用minio替代文件系统的实战教程

《Golang使用minio替代文件系统的实战教程》本文讨论项目开发中直接文件系统的限制或不足,接着介绍Minio对象存储的优势,同时给出Golang的实际示例代码,包括初始化客户端、读取minio对... 目录文件系统 vs Minio文件系统不足:对象存储:miniogolang连接Minio配置Min

Golang使用etcd构建分布式锁的示例分享

《Golang使用etcd构建分布式锁的示例分享》在本教程中,我们将学习如何使用Go和etcd构建分布式锁系统,分布式锁系统对于管理对分布式系统中共享资源的并发访问至关重要,它有助于维护一致性,防止竞... 目录引言环境准备新建Go项目实现加锁和解锁功能测试分布式锁重构实现失败重试总结引言我们将使用Go作

QT实现TCP客户端自动连接

《QT实现TCP客户端自动连接》这篇文章主要为大家详细介绍了QT中一个TCP客户端自动连接的测试模型,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录版本 1:没有取消按钮 测试效果测试代码版本 2:有取消按钮测试效果测试代码版本 1:没有取消按钮 测试效果缺陷:无法手动停

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]