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

news2024/11/18 23:24:21

文章目录

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

TCP 端口扫描器

非并发版本

package main

import (
	"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 main

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

func main() {
	start := time.Now()
	var wg sync.WaitGroup
	for 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) / 1e9
	fmt.Printf("/n/n%d seconds", elapsed)
}

goroutine 池并发版 TCP 端口扫描器

在这里插入图片描述

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

package main

import (
	"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 <- 0
			continue
		}
		conn.Close()
		//成功
		results <- p
	}
}

func main() {
	start := time.Now()

	ports := make(chan int, 100)
	results := make(chan int)

	//采用slice类型保存结果
	var openports []int
	var closeports []int

	//创建500个goroutine
	for i := 0; i < 500; i++ {
		go worker(ports, results)
	}

	//发送任务 需要单独的goroutine
	go func() {
		for i := 1; i < 65535; i++ {
			ports <- i
		}
	}()

	//接收结果 在主goroutine中完成
	for i := 1; i < 65535; i++ {
		port := <-results
		if 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) / 1e9
	fmt.Printf("\n\n%d seconds", elapsed)
}

运行

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

22 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。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1294762.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

HarmonyOS学习 第1节 DevEco Studio配置

俗话说的好&#xff0c;工欲善其事,必先利其器。我们先下载官方的开发工具DevEco Studio. 下载完成后&#xff0c;进行安装。 双击DevEco Studio&#xff0c;点击Next按照指引完成安装 重新启动DevEco&#xff0c;点击 Agree 进入环境配置&#xff0c;安装Node.js和ohpm 点击Ne…

网络编程基础api

1. IP 协议 1.1 IP 分片 &#xff08;1&#xff09;IP 分片和重组主要依靠 IP 头部三个字段&#xff1a;数据报标识、标志和片偏移 以太网帧的 MTU 是 1500 字节&#xff1b; 一个每个分片都有自己的 IP 头部&#xff0c;它们都具有相同的标识值&#xff0c;有不同的片偏移…

智能优化算法应用:基于孔雀算法无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于孔雀算法无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于孔雀算法无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.孔雀算法4.实验参数设定5.算法结果6.参考文献7.MATLAB…

十二要素超声波气象站-气象站科普百科

随着科技的发展&#xff0c;人们对气象信息的关注度越来越高。 一、十二要素超声波气象站实时监测 WX-CSQX12 十二要素超声波气象站通过超声波测量技术&#xff0c;对温度、湿度、风速、风向、气压、雨量、蒸发量等十二个气象要素进行实时监测。 二、智能分析 十二要素超声…

家电制造数字孪生5G智能工厂可视化系统,加速家电制造产业数字化转型

5G数字孪生、三维可视化与工业互联网的融合加速中国新型工业化进程&#xff0c;助推我国从制造大国迈进制造强国。家电行业是中国最具国际竞争力的产业之一&#xff0c;在企业数字化转型中&#xff0c;要求企业从生产设备到数字化系统&#xff0c;一系列的数字化、智能化改革已…

爱智EdgerOS之深入解析安全可靠的开放协议SDDC

一、协议简介 在 EdgerOS 的智慧生态场景中&#xff0c;许多智能设备或传感器的生命周期都与 SDDC 协议息息相关&#xff0c;这些设备可能是使用 libsddc 智能配网技术开发的&#xff0c;也有可能是因为主要功能上是使用其他技术如 MQTT、LoRa 等但是设备的上下线依然是使用上…

测试文档---智力冲刺

文章目录 项目背景测试计划UI测试接口测试手工测试 测试总结 项目背景 项目描述&#xff1a;“智力冲刺”是一款网页小游戏&#xff0c;就像我们平时看到的网页游戏一样&#xff0c;前端页面负责展示游戏效果&#xff0c;后端服务器来实现游戏的逻辑。在我们的“智力冲刺”游戏…

如何解压没有密码的7-zip文件?

7z压缩包设置了密码&#xff0c;解压的时候就需要输入正确对密码才能顺利解压出文件&#xff0c;正常当我们解压文件或者删除密码的时候&#xff0c;虽然方法多&#xff0c;但是都需要输入正确的密码才能完成。忘记密码就无法进行操作。 那么&#xff0c;忘记了7z压缩包的密码…

C //习题10.8 将第7题结果仍存入原有的“stu_sort“文件而不另建立新文件。

C程序设计 &#xff08;第四版&#xff09; 谭浩强 习题10.8 习题10.8 将第7题结果仍存入原有的"stu_sort"文件而不另建立新文件。 IDE工具&#xff1a;VS2010 Note: 使用不同的IDE工具可能有部分差异。 说明&#xff1a;此题同习题10.7的代码&#xff0c;唯一的区…

LangChain 23 Agents中的Tools用于增强和扩展智能代理agent的功能

LangChain系列文章 LangChain 实现给动物取名字&#xff0c;LangChain 2模块化prompt template并用streamlit生成网站 实现给动物取名字LangChain 3使用Agent访问Wikipedia和llm-math计算狗的平均年龄LangChain 4用向量数据库Faiss存储&#xff0c;读取YouTube的视频文本搜索I…

KST指标底背离选股公式,通过变动率ROC合成动量震荡指标

KST指标&#xff08;KnowSureThing&#xff09;是由马丁普林斯&#xff08;Martin Pring&#xff09;于1992年发明的技术分析指标&#xff0c;目的在于及时识别价格趋势的变化和转折点&#xff0c;同时避免短期震荡指标不稳定的缺点。KST指标结合了四个周期的ROC&#xff08;变…

学习记录---kubernetes中备份和恢复etcd

一、简介 ETCD是kubernetes的重要组成部分&#xff0c;它主要用于存储kubernetes的所有元数据&#xff0c;我们在kubernetes中的所有资源(node、pod、deployment、service等)&#xff0c;如果该组件出现问题&#xff0c;则可能会导致kubernetes无法使用、资源丢失等情况。因此…

HarmonyOS学习 第2节 DevEco Studio工程介绍

工程配置页 界面布局介绍 代码编辑区、通知栏、工程目录区、预览区 工程目录区 便于理解&#xff0c;可以切换为 Ohos AppScope主要用于存放整个应用公共的信息与资源 entry默认的初始模块ets文件用于存放编写的代码文件configuration存放相应模块的配置文件resources对应模块…

上证指数近十年走势图

上证指数是中国股市的晴雨表&#xff0c;其近十年的走势图展现了中国经济波动、政策变化、国际形势等多重因素对股市的影响。让我们一起通过这张图&#xff0c;深入探讨上证指数的波动&#xff0c;了解其中的因果关系和背后的故事。 2013-2015&#xff1a;震荡上行 回顾近十年…

【FPGA】Verilog:BCD 加法器的实现

0x00 XOR 运算在 2 的补码加减法中的应用 2 的补码加减法的特点是&#xff0c;当从某个数中减去负数时&#xff0c;将其转换为正数的加法来计算&#xff0c;并将减去正数的情况转换为负数的加法来计算&#xff0c;从而将所有减法运算转换为加法运算。在这种情况下&#xff0c;…

windows系统nodeJs报错node-sass npm ERR! command failed

报错信息 npm WARN deprecated request2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142 npm WARN deprecated tar2.2.2: This version of tar is no longer supported, and will not receive security updates. Please upgrade asa…

DDD架构思想专栏一《初识领域驱动设计DDD落地》

引言 最近准备给自己之前写的项目做重构&#xff0c;这是一个单体架构的小项目&#xff0c;后端采用的是最常见的三层架构。因为项目比较简单&#xff0c;其实采用三层架构就完全够了。但是呢&#xff0c;小编最近在做DDD架构的项目&#xff0c;于是就先拿之前写的一个老项目试…

解决Eslint和Prettier关于三元运算符的冲突问题

三元运算符Prettier的格式化 三元运算符Eslint的格式要求 解决办法 // eslint加入配置&#xff0c;屏蔽标红报错indent: [error, 2, { ignoredNodes: [ConditionalExpression] }]效果

HCIP —— BGP 基础 (上)

BGP --- 边界网关协议 &#xff08;路径矢量协议&#xff09; IGP --- 内部网关协议 --- OSPF RIP ISIS EGP --- 外部网关协议 --- EGP BGP AS --- 自治系统 由单一的组织或者机构独立维护的网络设备以及网络资源的集合。 因 网络范围太大 需 自治 。 为区分不同的AS&#…

智能优化算法应用:基于浣熊算法无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于浣熊算法无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于浣熊算法无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.浣熊算法4.实验参数设定5.算法结果6.参考文献7.MATLAB…