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

相关文章

Unity新手入门学习殿堂级知识详细讲解(图文)

《Unity新手入门学习殿堂级知识详细讲解(图文)》Unity是一款跨平台游戏引擎,支持2D/3D及VR/AR开发,核心功能模块包括图形、音频、物理等,通过可视化编辑器与脚本扩展实现开发,项目结构含A... 目录入门概述什么是 UnityUnity引擎基础认知编辑器核心操作Unity 编辑器项目模式分类工程

Python学习笔记之getattr和hasattr用法示例详解

《Python学习笔记之getattr和hasattr用法示例详解》在Python中,hasattr()、getattr()和setattr()是一组内置函数,用于对对象的属性进行操作和查询,这篇文章... 目录1.getattr用法详解1.1 基本作用1.2 示例1.3 原理2.hasattr用法详解2.

Linux之UDP和TCP报头管理方式

《Linux之UDP和TCP报头管理方式》文章系统讲解了传输层协议UDP与TCP的核心区别:UDP无连接、不可靠,适合实时传输(如视频),通过端口号标识应用;TCP有连接、可靠,通过确认应答、序号、窗... 目录一、关于端口号1.1 端口号的理解1.2 端口号范围的划分1.3 认识知名端口号1.4 一个进程

全面解析Golang 中的 Gorilla CORS 中间件正确用法

《全面解析Golang中的GorillaCORS中间件正确用法》Golang中使用gorilla/mux路由器配合rs/cors中间件库可以优雅地解决这个问题,然而,很多人刚开始使用时会遇到配... 目录如何让 golang 中的 Gorilla CORS 中间件正确工作一、基础依赖二、错误用法(很多人一开

golang程序打包成脚本部署到Linux系统方式

《golang程序打包成脚本部署到Linux系统方式》Golang程序通过本地编译(设置GOOS为linux生成无后缀二进制文件),上传至Linux服务器后赋权执行,使用nohup命令实现后台运行,完... 目录本地编译golang程序上传Golang二进制文件到linux服务器总结本地编译Golang程序

golang版本升级如何实现

《golang版本升级如何实现》:本文主要介绍golang版本升级如何实现问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录golanwww.chinasem.cng版本升级linux上golang版本升级删除golang旧版本安装golang最新版本总结gola

golang中reflect包的常用方法

《golang中reflect包的常用方法》Go反射reflect包提供类型和值方法,用于获取类型信息、访问字段、调用方法等,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录reflect包方法总结类型 (Type) 方法值 (Value) 方法reflect包方法总结

Golang如何对cron进行二次封装实现指定时间执行定时任务

《Golang如何对cron进行二次封装实现指定时间执行定时任务》:本文主要介绍Golang如何对cron进行二次封装实现指定时间执行定时任务问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录背景cron库下载代码示例【1】结构体定义【2】定时任务开启【3】使用示例【4】控制台输出总结背景

Golang如何用gorm实现分页的功能

《Golang如何用gorm实现分页的功能》:本文主要介绍Golang如何用gorm实现分页的功能方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录背景go库下载初始化数据【1】建表【2】插入数据【3】查看数据4、代码示例【1】gorm结构体定义【2】分页结构体

在Golang中实现定时任务的几种高效方法

《在Golang中实现定时任务的几种高效方法》本文将详细介绍在Golang中实现定时任务的几种高效方法,包括time包中的Ticker和Timer、第三方库cron的使用,以及基于channel和go... 目录背景介绍目的和范围预期读者文档结构概述术语表核心概念与联系故事引入核心概念解释核心概念之间的关系