python、ruby、go、java写的端口扫描工具

编写的简单端口扫描器的示例代码

python

python 复制代码
import socket

def scan_ports(host, port_range):
    open_ports = []
    for port in range(*port_range):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(1)
            if s.connect_ex((host, port)) == 0:
                open_ports.append(port)
    return open_ports

host = "127.0.0.1"
port_range = (1, 1025)
open_ports = scan_ports(host, port_range)
print(f"Open ports on {host}: {open_ports}")

ruby

ruby 复制代码
require 'socket'
require 'timeout'

def scan_ports(host, port_range)
  open_ports = []
  port_range.each do |port|
    begin
      Timeout::timeout(1) do
        TCPSocket.new(host, port).close
        open_ports << port
      end
    rescue Errno::ECONNREFUSED, Timeout::Error
    end
  end
  open_ports
end

host = "127.0.0.1"
port_range = 1..1024
open_ports = scan_ports(host, port_range)
puts "Open ports on #{host}: #{open_ports}"

go

go 复制代码
package main

import (
    "fmt"
    "net"
    "strconv"
    "time"
)

func scanPort(host string, port int) bool {
    address := host + ":" + strconv.Itoa(port)
    conn, err := net.DialTimeout("tcp", address, time.Second)
    if err != nil {
        return false
    }
    defer conn.Close()
    return true
}

func main() {
    host := "127.0.0.1"
    var openPorts []int
    for port := 1; port <= 1024; port++ {
        if scanPort(host, port) {
            openPorts = append(openPorts, port)
        }
    }
    fmt.Printf("Open ports on %s: %v\n", host, openPorts)
}

java

java 复制代码
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class PortScanner {
    public static List<Integer> scanPorts(String host, int startPort, int endPort) {
        List<Integer> openPorts = new ArrayList<>();
        for (int port = startPort; port <= endPort; port++) {
            try (Socket socket = new Socket(host, port)) {
                openPorts.add(port);
            } catch (IOException ignored) {
            }
        }
        return openPorts;
    }

    public static void main(String[] args) {
        String host = "127.0.0.1";
        List<Integer> openPorts = scanPorts(host, 1, 1024);
        System.out.println("Open ports on " + host + ": " + openPorts);
    }
}
相关推荐
a***56061 小时前
Windows上安装Go并配置环境变量(图文步骤)
开发语言·windows·golang
d***95622 小时前
爬虫自动化(DrissionPage)
爬虫·python·自动化
APIshop2 小时前
Python 零基础写爬虫:一步步抓取商品详情(超细详解)
开发语言·爬虫·python
二川bro2 小时前
AutoML自动化机器学习:Python实战指南
python·机器学习·自动化
杨超越luckly3 小时前
基于 Overpass API 的城市电网基础设施与 POI 提取与可视化
python·数据可视化·openstreetmap·电力数据·overpass api
q***23573 小时前
python的sql解析库-sqlparse
数据库·python·sql
18你磊哥4 小时前
Django WEB 简单项目创建与结构讲解
前端·python·django·sqlite
月殇_木言4 小时前
Python期末复习
开发语言·python
BBB努力学习程序设计6 小时前
Python面向对象编程:从代码搬运工到架构师
python·pycharm
rising start6 小时前
五、python正则表达式
python·正则表达式