├── go.mod ├── assets ├── demo.jpg └── tcping_releases.jpg ├── .gitignore ├── test.sh ├── compiler.sh ├── .github └── workflows │ └── release.yml ├── install.sh ├── README.md ├── install_cn.sh ├── src └── main.go └── LICENSE /go.mod: -------------------------------------------------------------------------------- 1 | module tcping 2 | 3 | go 1.25.5 4 | -------------------------------------------------------------------------------- /assets/demo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nodeseeker/tcping/HEAD/assets/demo.jpg -------------------------------------------------------------------------------- /assets/tcping_releases.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nodeseeker/tcping/HEAD/assets/tcping_releases.jpg -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # If you prefer the allow list template instead of the deny list, see community template: 2 | # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore 3 | # 4 | # Binaries for programs and plugins 5 | *.exe 6 | *.exe~ 7 | *.dll 8 | *.so 9 | *.dylib 10 | 11 | # Test binary, built with `go test -c` 12 | *.test 13 | 14 | # Output of the go coverage tool, specifically when used with LiteIDE 15 | *.out 16 | 17 | # Dependency directories (remove the comment below to include it) 18 | # vendor/ 19 | 20 | # Go workspace file 21 | go.work 22 | go.work.sum 23 | 24 | # env file 25 | .env 26 | 27 | # binaries 28 | bin/ 29 | tcping -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | 4 | # 定义测试目标 5 | IPV4_TARGET="1.1.1.1" 6 | IPV6_TARGET="2606:4700:4700::1111" 7 | DOMAIN_TARGET="cloudflare.com" 8 | PORT="80" 9 | HTTPS_PORT="443" 10 | 11 | # 定义测试函数 12 | function run_test() { 13 | echo "Running test: $1" 14 | echo "Command: $2" 15 | eval "$2" 16 | if [ $? -eq 0 ]; then 17 | echo "Test passed: $1" 18 | else 19 | echo "Test failed: $1" 20 | fi 21 | echo "-----------------------------------" 22 | } 23 | 24 | # 测试 IPv4 地址 25 | run_test "IPv4 Address Test" "./tcping $IPV4_TARGET $PORT" 26 | 27 | # 测试 IPv6 地址 28 | run_test "IPv6 Address Test" "./tcping -6 $IPV6_TARGET $PORT" 29 | 30 | # 测试域名解析 (IPv4) 31 | run_test "Domain IPv4 Test" "./tcping $DOMAIN_TARGET $HTTPS_PORT" 32 | 33 | # 测试域名解析 (IPv6) 34 | run_test "Domain IPv6 Test" "./tcping -6 $DOMAIN_TARGET $HTTPS_PORT" 35 | 36 | # 测试指定次数 37 | run_test "Ping with Count Test" "./tcping -n 3 $IPV4_TARGET $PORT" 38 | 39 | # 测试指定间隔时间 40 | run_test "Ping with Interval Test" "./tcping -t 2000 $IPV4_TARGET $PORT" 41 | 42 | # 测试超时时间 43 | run_test "Ping with Timeout Test" "./tcping -w 100 $IPV4_TARGET $PORT" 44 | 45 | # 综合测试 46 | run_test "Comprehensive Test" "./tcping -6 -n 5 -t 2 $DOMAIN_TARGET $HTTPS_PORT" 47 | -------------------------------------------------------------------------------- /compiler.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # 源代码路径 4 | SRC_PATH="./src/main.go" 5 | # 输出目录 6 | OUT_DIR="./bin" 7 | # 程序名 8 | APP_NAME="tcping" 9 | 10 | # 需要编译的目标平台和架构 11 | PLATFORMS=( 12 | "darwin/amd64" 13 | "darwin/arm64" 14 | "linux/386" 15 | "linux/amd64" 16 | "linux/arm" 17 | "linux/arm64" 18 | "linux/loong64" 19 | "windows/386" 20 | "windows/amd64" 21 | "windows/arm" 22 | "windows/arm64" 23 | ) 24 | 25 | # 清理之前的编译产物 26 | rm -rf $OUT_DIR 27 | mkdir -p $OUT_DIR 28 | 29 | # 初始化 SHA256SUMS 文件 30 | > "$OUT_DIR/SHA256SUMS.txt" 31 | 32 | # 编译并压缩每个平台 33 | for PLATFORM in "${PLATFORMS[@]}"; do 34 | # 获取平台的 GOOS 和 GOARCH 35 | GOOS=$(echo $PLATFORM | cut -d'/' -f1) 36 | GOARCH=$(echo $PLATFORM | cut -d'/' -f2) 37 | 38 | # 设置输出文件路径 39 | OUT_FILE="$OUT_DIR/$APP_NAME" 40 | 41 | # 设置环境变量并编译 42 | echo "编译 ${GOOS}/${GOARCH}..." 43 | CGO_ENABLED=0 GOOS=$GOOS GOARCH=$GOARCH go build -trimpath -ldflags="-w -s" -o "$OUT_FILE" $SRC_PATH 44 | 45 | # 判断是否是 Windows 平台,需要添加 .exe 扩展名 46 | if [ "$GOOS" == "windows" ]; then 47 | mv "$OUT_FILE" "$OUT_FILE.exe" 48 | OUT_FILE="$OUT_FILE.exe" 49 | fi 50 | 51 | # 压缩成 .zip 文件 52 | echo "压缩 ${OUT_FILE}..." 53 | zip -j "$OUT_DIR/$APP_NAME-${GOOS}-${GOARCH}.zip" "$OUT_FILE" 54 | 55 | # 计算 SHA256 值并追加到 SHA256SUMS.txt 中 56 | sha256sum "$OUT_DIR/$APP_NAME-${GOOS}-${GOARCH}.zip" >> "$OUT_DIR/SHA256SUMS.txt" 57 | 58 | # 清理中间文件 59 | rm "$OUT_FILE" 60 | done 61 | 62 | echo "编译和压缩完成,所有文件已存储在 $OUT_DIR 目录下。" 63 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Build and Release 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | version: 7 | description: 'Release version (e.g., v1.0.0)' 8 | required: true 9 | default: 'v1.0.0' 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | permissions: 15 | contents: write 16 | 17 | steps: 18 | - name: Checkout code 19 | uses: actions/checkout@v4 20 | 21 | - name: Set up Go 22 | uses: actions/setup-go@v5 23 | with: 24 | go-version: '1.25' 25 | 26 | - name: Create output directory 27 | run: mkdir -p bin 28 | 29 | - name: Build for all platforms 30 | env: 31 | CGO_ENABLED: 0 32 | run: | 33 | # 定义所有目标平台 34 | platforms=( 35 | "darwin/amd64" 36 | "darwin/arm64" 37 | "linux/386" 38 | "linux/amd64" 39 | "linux/arm" 40 | "linux/arm64" 41 | "linux/loong64" 42 | "windows/386" 43 | "windows/amd64" 44 | "windows/arm" 45 | "windows/arm64" 46 | ) 47 | 48 | for platform in "${platforms[@]}"; do 49 | GOOS=$(echo $platform | cut -d'/' -f1) 50 | GOARCH=$(echo $platform | cut -d'/' -f2) 51 | 52 | echo "Building for ${GOOS}/${GOARCH}..." 53 | 54 | # 设置输出文件名 55 | output_name="tcping" 56 | if [ "$GOOS" = "windows" ]; then 57 | output_name="tcping.exe" 58 | fi 59 | 60 | # 编译 61 | CGO_ENABLED=0 GOOS=$GOOS GOARCH=$GOARCH go build -trimpath -ldflags="-w -s" -o "$output_name" ./src/main.go 62 | 63 | # 打包成 zip 64 | zip_name="tcping-${GOOS}-${GOARCH}.zip" 65 | zip -j "bin/${zip_name}" "$output_name" 66 | 67 | # 清理编译产物 68 | rm "$output_name" 69 | 70 | echo "Created bin/${zip_name}" 71 | done 72 | 73 | - name: Generate SHA256SUMS 74 | run: | 75 | cd bin 76 | sha256sum *.zip > SHA256SUMS.txt 77 | cat SHA256SUMS.txt 78 | 79 | - name: Upload artifacts 80 | uses: actions/upload-artifact@v4 81 | with: 82 | name: tcping-binaries 83 | path: bin/* 84 | 85 | - name: Create Release 86 | uses: softprops/action-gh-release@v2 87 | with: 88 | tag_name: ${{ github.event.inputs.version }} 89 | name: Release ${{ github.event.inputs.version }} 90 | draft: false 91 | prerelease: false 92 | files: | 93 | bin/*.zip 94 | bin/SHA256SUMS.txt 95 | env: 96 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 97 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # tcping 安装/更新/卸载脚本 4 | # 用于自动安装、更新或卸载 tcping 工具 5 | # 支持架构:amd64, arm64, 386, arm, loong64 6 | # 7 | # 使用方法: 8 | # sudo ./install.sh # 安装或更新 tcping 9 | # sudo ./install.sh -u # 卸载 tcping 10 | # sudo ./install.sh -f # 强制安装(跳过确认) 11 | # sudo ./install.sh -v # 详细输出 12 | # 13 | 14 | set -euo pipefail # 严格模式:遇到错误立即退出,未定义变量报错,管道错误传播 15 | 16 | # 颜色定义 17 | readonly RED='\033[0;31m' 18 | readonly GREEN='\033[0;32m' 19 | readonly YELLOW='\033[1;33m' 20 | readonly BLUE='\033[0;34m' 21 | readonly CYAN='\033[0;36m' 22 | readonly BOLD='\033[1m' 23 | readonly NC='\033[0m' # No Color 24 | 25 | # 基本配置 26 | readonly INSTALL_DIR="/usr/local/bin" 27 | readonly TCPING_BIN="tcping" 28 | readonly GITHUB_API="https://api.github.com/repos/nodeseeker/tcping" 29 | readonly GITHUB_REPO="https://github.com/nodeseeker/tcping" 30 | readonly TEMP_DIR="/tmp/tcping_install" 31 | 32 | # 全局变量 33 | VERBOSE=false 34 | FORCE=false 35 | UNINSTALL=false 36 | CURRENT_VERSION="" 37 | LATEST_VERSION="" 38 | 39 | # 打印函数 40 | print_info() { 41 | echo -e "${BLUE}[INFO]${NC} $1" 42 | } 43 | 44 | print_success() { 45 | echo -e "${GREEN}[SUCCESS]${NC} $1" 46 | } 47 | 48 | print_warning() { 49 | echo -e "${YELLOW}[WARNING]${NC} $1" 50 | } 51 | 52 | print_error() { 53 | echo -e "${RED}[ERROR]${NC} $1" >&2 54 | } 55 | 56 | print_verbose() { 57 | if [[ "$VERBOSE" == true ]]; then 58 | echo -e "${CYAN}[VERBOSE]${NC} $1" 59 | fi 60 | } 61 | 62 | print_title() { 63 | echo -e "${BOLD}${BLUE}$1${NC}" 64 | } 65 | 66 | # 显示帮助信息 67 | show_help() { 68 | cat << EOF 69 | TCPing 安装脚本 70 | 71 | 用法: $0 [选项] 72 | 73 | 选项: 74 | -u, --uninstall 卸载 tcping 75 | -f, --force 强制安装(跳过确认) 76 | -v, --verbose 详细输出 77 | -h, --help 显示此帮助信息 78 | 79 | 支持的架构: amd64, arm64, 386, arm, loong64 80 | 81 | 示例: 82 | sudo $0 # 安装或更新 tcping 83 | sudo $0 -u # 卸载 tcping 84 | sudo $0 -f # 强制安装 85 | sudo $0 -v # 详细输出安装过程 86 | 87 | EOF 88 | } 89 | 90 | # 检查 root 权限 91 | check_root() { 92 | if [[ $EUID -ne 0 ]]; then 93 | print_error "此脚本需要 root 权限运行" 94 | print_info "请使用: sudo $0" 95 | exit 1 96 | fi 97 | print_verbose "Root 权限检查通过" 98 | } 99 | 100 | # 检查系统依赖 101 | check_dependencies() { 102 | local missing_deps=() 103 | local deps=("curl" "unzip" "grep" "awk") 104 | 105 | print_verbose "检查系统依赖..." 106 | 107 | for dep in "${deps[@]}"; do 108 | if ! command -v "$dep" &> /dev/null; then 109 | missing_deps+=("$dep") 110 | fi 111 | done 112 | 113 | if [[ ${#missing_deps[@]} -gt 0 ]]; then 114 | print_warning "缺少以下依赖程序: ${missing_deps[*]}" 115 | echo -n "是否安装缺少的依赖? [y/N]: " 116 | 117 | if [[ "$FORCE" == true ]]; then 118 | echo "y (强制模式)" 119 | install_dependencies "${missing_deps[@]}" 120 | else 121 | read -r response 122 | if [[ "$response" =~ ^[Yy]$ ]]; then 123 | install_dependencies "${missing_deps[@]}" 124 | else 125 | print_error "缺少必要依赖,无法继续安装" 126 | exit 1 127 | fi 128 | fi 129 | else 130 | print_verbose "所有依赖已满足" 131 | fi 132 | } 133 | 134 | # 安装依赖 135 | install_dependencies() { 136 | local deps=("$@") 137 | print_info "正在安装依赖: ${deps[*]}" 138 | 139 | if command -v apt &> /dev/null; then 140 | apt update && apt install -y "${deps[@]}" 141 | elif command -v yum &> /dev/null; then 142 | yum install -y "${deps[@]}" 143 | elif command -v dnf &> /dev/null; then 144 | dnf install -y "${deps[@]}" 145 | elif command -v pacman &> /dev/null; then 146 | pacman -S --noconfirm "${deps[@]}" 147 | elif command -v apk &> /dev/null; then 148 | apk add "${deps[@]}" 149 | elif command -v zypper &> /dev/null; then 150 | zypper install -y "${deps[@]}" 151 | else 152 | print_error "无法识别的包管理器,请手动安装: ${deps[*]}" 153 | exit 1 154 | fi 155 | 156 | print_success "依赖安装完成" 157 | } 158 | 159 | # 获取系统架构 160 | get_arch() { 161 | local arch 162 | arch=$(uname -m) 163 | 164 | case "$arch" in 165 | x86_64|amd64) 166 | echo "amd64" 167 | ;; 168 | aarch64|arm64) 169 | echo "arm64" 170 | ;; 171 | i386|i686) 172 | echo "386" 173 | ;; 174 | armv6l|armv7l|arm*) 175 | echo "arm" 176 | ;; 177 | loongarch64) 178 | echo "loong64" 179 | ;; 180 | *) 181 | print_error "不支持的架构: $arch" 182 | print_info "支持的架构: amd64, arm64, 386, arm, loong64" 183 | exit 1 184 | ;; 185 | esac 186 | } 187 | 188 | # 获取当前已安装版本 189 | get_current_version() { 190 | if command -v "$TCPING_BIN" &> /dev/null; then 191 | # 执行 tcping --version 并解析版本号 192 | local version_output 193 | version_output=$("$TCPING_BIN" --version 2>/dev/null || echo "") 194 | if [[ -n "$version_output" ]]; then 195 | # 提取版本号,格式类似 "TCPing 版本 v1.7.1" 196 | CURRENT_VERSION=$(echo "$version_output" | grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' | head -1) 197 | fi 198 | fi 199 | 200 | if [[ -n "$CURRENT_VERSION" ]]; then 201 | print_verbose "当前安装版本: $CURRENT_VERSION" 202 | else 203 | print_verbose "未检测到已安装的 tcping" 204 | fi 205 | } 206 | 207 | # 获取最新版本 208 | get_latest_version() { 209 | print_verbose "正在获取最新版本信息..." 210 | 211 | local api_response 212 | api_response=$(curl -s "$GITHUB_API/releases/latest" 2>/dev/null || echo "") 213 | 214 | if [[ -n "$api_response" ]]; then 215 | LATEST_VERSION=$(echo "$api_response" | grep -oE '"tag_name":\s*"[^"]*"' | cut -d'"' -f4) 216 | fi 217 | 218 | if [[ -z "$LATEST_VERSION" ]]; then 219 | print_warning "无法获取最新版本信息,使用默认版本 v1.7.1" 220 | LATEST_VERSION="v1.7.1" 221 | fi 222 | 223 | print_verbose "最新版本: $LATEST_VERSION" 224 | } 225 | 226 | # 比较版本 227 | compare_versions() { 228 | local current="$1" 229 | local latest="$2" 230 | 231 | # 移除 v 前缀 232 | current=${current#v} 233 | latest=${latest#v} 234 | 235 | # 使用 sort 比较版本号 236 | local higher 237 | higher=$(printf '%s\n%s\n' "$current" "$latest" | sort -V | tail -n1) 238 | 239 | if [[ "$higher" == "$latest" && "$current" != "$latest" ]]; then 240 | return 1 # 需要更新 241 | else 242 | return 0 # 已是最新或更高版本 243 | fi 244 | } 245 | 246 | # 下载并安装 tcping 247 | install_tcping() { 248 | local arch 249 | arch=$(get_arch) 250 | 251 | print_info "正在为 $arch 架构下载 tcping $LATEST_VERSION..." 252 | 253 | # 创建临时目录 254 | mkdir -p "$TEMP_DIR" 255 | cd "$TEMP_DIR" 256 | 257 | # 构造下载 URL - 匹配实际的文件命名格式 258 | local download_url="$GITHUB_REPO/releases/download/$LATEST_VERSION/tcping-linux-$arch.zip" 259 | 260 | print_verbose "下载 URL: $download_url" 261 | 262 | # 下载文件 263 | if ! curl -L -o "tcping.zip" "$download_url"; then 264 | print_error "下载失败" 265 | cleanup 266 | exit 1 267 | fi 268 | 269 | # 解压文件 270 | print_verbose "正在解压文件..." 271 | if ! unzip -q "tcping.zip"; then 272 | print_error "解压失败" 273 | cleanup 274 | exit 1 275 | fi 276 | 277 | # 查找二进制文件 278 | local binary_file 279 | binary_file=$(find . -name "$TCPING_BIN" -type f | head -1) 280 | 281 | if [[ -z "$binary_file" ]]; then 282 | print_error "未找到二进制文件" 283 | cleanup 284 | exit 1 285 | fi 286 | 287 | # 安装二进制文件 288 | print_verbose "正在安装到 $INSTALL_DIR/$TCPING_BIN..." 289 | if ! cp "$binary_file" "$INSTALL_DIR/$TCPING_BIN"; then 290 | print_error "安装失败:无法复制文件到 $INSTALL_DIR" 291 | cleanup 292 | exit 1 293 | fi 294 | 295 | # 设置执行权限 296 | chmod +x "$INSTALL_DIR/$TCPING_BIN" 297 | 298 | # 清理临时文件 299 | cleanup 300 | 301 | print_success "tcping $LATEST_VERSION 安装完成!" 302 | 303 | # 验证安装 304 | if command -v "$TCPING_BIN" &> /dev/null; then 305 | print_info "安装验证:" 306 | "$TCPING_BIN" --version 307 | else 308 | print_warning "安装完成,但 $TCPING_BIN 不在 PATH 中" 309 | print_info "请确保 $INSTALL_DIR 在您的 PATH 环境变量中" 310 | fi 311 | } 312 | 313 | # 卸载 tcping 314 | uninstall_tcping() { 315 | if [[ -f "$INSTALL_DIR/$TCPING_BIN" ]]; then 316 | print_info "正在卸载 tcping..." 317 | 318 | if [[ "$FORCE" == false ]]; then 319 | echo -n "确认卸载 tcping? [y/N]: " 320 | read -r response 321 | if [[ ! "$response" =~ ^[Yy]$ ]]; then 322 | print_info "取消卸载" 323 | exit 0 324 | fi 325 | fi 326 | 327 | rm -f "$INSTALL_DIR/$TCPING_BIN" 328 | print_success "tcping 已成功卸载" 329 | else 330 | print_warning "tcping 未安装" 331 | fi 332 | } 333 | 334 | # 清理临时文件 335 | cleanup() { 336 | if [[ -d "$TEMP_DIR" ]]; then 337 | rm -rf "$TEMP_DIR" 338 | print_verbose "临时文件已清理" 339 | fi 340 | } 341 | 342 | # 主函数 343 | main() { 344 | # 解析命令行参数 345 | while [[ $# -gt 0 ]]; do 346 | case $1 in 347 | -u|--uninstall) 348 | UNINSTALL=true 349 | shift 350 | ;; 351 | -f|--force) 352 | FORCE=true 353 | shift 354 | ;; 355 | -v|--verbose) 356 | VERBOSE=true 357 | shift 358 | ;; 359 | -h|--help) 360 | show_help 361 | exit 0 362 | ;; 363 | *) 364 | print_error "未知选项: $1" 365 | show_help 366 | exit 1 367 | ;; 368 | esac 369 | done 370 | 371 | # 显示标题 372 | print_title "TCPing 安装脚本" 373 | echo 374 | 375 | # 检查权限 376 | check_root 377 | 378 | # 如果是卸载模式 379 | if [[ "$UNINSTALL" == true ]]; then 380 | uninstall_tcping 381 | exit 0 382 | fi 383 | 384 | # 检查依赖 385 | check_dependencies 386 | 387 | # 获取版本信息 388 | get_current_version 389 | get_latest_version 390 | 391 | # 检查是否需要安装或更新 392 | if [[ -z "$CURRENT_VERSION" ]]; then 393 | print_info "检测到 tcping 未安装" 394 | 395 | if [[ "$FORCE" == false ]]; then 396 | echo -n "是否安装 tcping $LATEST_VERSION? [Y/n]: " 397 | read -r response 398 | if [[ "$response" =~ ^[Nn]$ ]]; then 399 | print_info "取消安装" 400 | exit 0 401 | fi 402 | fi 403 | 404 | install_tcping 405 | else 406 | print_info "检测到已安装版本: $CURRENT_VERSION" 407 | 408 | if compare_versions "$CURRENT_VERSION" "$LATEST_VERSION"; then 409 | print_success "您已安装最新版本 $CURRENT_VERSION" 410 | 411 | if [[ "$FORCE" == true ]]; then 412 | print_info "强制重新安装..." 413 | install_tcping 414 | fi 415 | else 416 | print_info "发现新版本: $LATEST_VERSION" 417 | 418 | if [[ "$FORCE" == false ]]; then 419 | echo -n "是否更新到 $LATEST_VERSION? [Y/n]: " 420 | read -r response 421 | if [[ "$response" =~ ^[Nn]$ ]]; then 422 | print_info "取消更新" 423 | exit 0 424 | fi 425 | fi 426 | 427 | install_tcping 428 | fi 429 | fi 430 | } 431 | 432 | # 设置清理陷阱 433 | trap cleanup EXIT INT TERM 434 | 435 | # 运行主函数 436 | main "$@" 437 | 438 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TCPing 2 | 3 | [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) 4 | [![Go Version](https://img.shields.io/badge/Go-1.25+-blue.svg)](https://golang.org/) 5 | [![Version](https://img.shields.io/badge/Version-v1.7.4-green.svg)](https://github.com/nodeseeker/tcping/releases) 6 | 7 | 一款基于Golang的高性能TCP Ping工具,支持IPv4、IPv6和域名解析,提供丰富的自定义选项和详细的连接信息展示。 8 | 9 |

10 | releases_example 11 |

12 | 13 | 14 | ## ✨ 功能概述 15 | 16 | **TCPing** 是一个轻量级、高效的 TCP 连接测试工具,具备以下特性: 17 | 18 | ### 🌐 多协议支持 19 | - 支持 IPv4 和 IPv6 地址解析 20 | - 支持标准IPv4点分十进制格式(如 `8.8.8.8`) 21 | - 智能域名解析,自动选择最优协议 22 | 23 | ### ⚙️ 灵活配置 24 | - 自定义目标端口(1-65535) 25 | - 可配置请求次数和发送间隔 26 | - 可调节连接超时时间 27 | - 支持无限次连续测试 28 | 29 | ### 🎨 友好输出 30 | - 彩色输出模式,直观显示结果状态 31 | - 详细模式显示完整连接信息 32 | - 实时统计信息(最小/最大/平均延迟) 33 | - 网络抖动(Jitter)计算,提供网络稳定性分析 34 | - 完善的错误处理和提示信息 35 | 36 | ### 🛠️ 使用便捷 37 | - 跨平台支持(Linux、Windows、macOS) 38 | - 多架构支持(amd64、arm64、386、arm、loong64) 39 | - 一键安装脚本,支持自动更新 40 | - 无依赖运行,开箱即用 41 | 42 | 43 | 44 | ## 📦 安装方法 45 | 46 | ### 方法一:手动安装 47 | 48 | #### 📥 下载预编译二进制文件 49 | 50 | 访问 [GitHub Releases](https://github.com/nodeseeker/tcping/releases) 页面,选择适合您系统的版本: 51 | 52 | ![releases_example](https://raw.githubusercontent.com/nodeseeker/tcping/refs/heads/main/assets/tcping_releases.jpg) 53 | 54 | #### 🗂️ 支持的平台和架构 55 | 56 | | 操作系统 | 支持架构 | 57 | |----------|----------| 58 | | **Linux** | amd64, 386, arm64, arm, loong64 | 59 | | **Windows** | amd64, 386, arm64, arm | 60 | | **macOS** | amd64, arm64 | 61 | 62 | 63 | #### 🔧 安装步骤 64 | 65 | 1. **下载对应版本**:根据您的系统选择合适的压缩包 66 | 2. **解压文件**:解压后得到 `tcping` 可执行文件 67 | 3. **配置环境**:将文件移动到系统PATH目录 68 | 69 | #### 📍 推荐安装位置 70 | 71 | - **Linux/macOS**:`/usr/local/bin/tcping` 72 | - **Windows**:`C:\Windows\System32\tcping.exe` 或添加到PATH环境变量 73 | 74 | #### 🛠️ 权限设置 75 | 对于Linux/Unix-like系统,如果非`root`用户无法使用,则需要在安装后,使用`root`执行一次以下命令即可确保可执行权限: 76 | ```bash 77 | chown root:root /usr/local/bin/tcping 78 | chmod +x /usr/local/bin/tcping 79 | ``` 80 | 81 | #### ✅ 验证安装 82 | 83 | ```bash 84 | tcping --version 85 | 86 | TCPing 版本 v1.8.0 87 | Copyright (c) 2026. All rights reserved. 88 | ``` 89 | 90 | 91 | 92 | ### 方法二: 93 | 94 | 一键安装脚本(推荐) 95 | 96 | #### 🌍 境外服务器 97 | ```bash 98 | bash <(curl -Ls https://raw.githubusercontent.com/nodeseeker/tcping/main/install.sh) --force 99 | ``` 100 | 101 | #### 🇨🇳 境内服务器(国内优化版) 102 | ```bash 103 | bash <(curl -Ls https://gh-proxy.com/raw.githubusercontent.com/nodeseeker/tcping/main/install_cn.sh) --force 104 | ``` 105 | 106 | > **注意:** 脚本会自动安装到 `/usr/local/bin` 目录,需要root权限 107 | 108 | #### 📋 安装脚本选项 109 | 110 | | 选项 | 长选项 | 说明 | 111 | |------|--------|------| 112 | | `-u` | `--uninstall` | 卸载 tcping | 113 | | `-f` | `--force` | 强制安装(跳过确认) | 114 | | `-v` | `--verbose` | 详细输出安装过程 | 115 | | `-h` | `--help` | 显示帮助信息 | 116 | 117 | #### 🔄 脚本功能特性 118 | - **智能检测**:自动检测系统架构和已安装版本 119 | - **版本管理**:支持安装、更新、卸载操作 120 | - **依赖处理**:自动检测并安装必要依赖(curl、unzip等) 121 | - **多源下载**:国内版本支持多个镜像源,提高下载成功率 122 | - **错误处理**:完善的错误处理和用户提示 123 | 124 | 125 | ## 🚀 使用方法 126 | 127 | ### 基本语法 128 | ```bash 129 | tcping [选项] <主机> [端口] 130 | ``` 131 | 132 | ### 📋 命令行选项 133 | 134 | | 短选项 | 长选项 | 描述 | 默认值 | 135 | |--------|---------|------|--------| 136 | | `-4` | `--ipv4` | 强制使用 IPv4 | 自动检测 | 137 | | `-6` | `--ipv6` | 强制使用 IPv6 | 自动检测 | 138 | | `-n` | `--count` | 发送请求的次数 | 无限 | 139 | | `-p` | `--port` | 指定要连接的端口 | 80 | 140 | | `-t` | `--interval` | 请求之间的间隔(毫秒) | 1000ms | 141 | | `-w` | `--timeout` | 连接超时时间(毫秒) | 1000ms | 142 | | `-c` | `--color` | 启用彩色输出 | 关闭 | 143 | | `-v` | `--verbose` | 启用详细模式(包含抖动统计) | 关闭 | 144 | | `-V` | `--version` | 显示版本信息 | - | 145 | | `-h` | `--help` | 显示帮助信息 | - | 146 | 147 | 148 | 149 | ## 📖 使用示例 150 | 151 | ### 🔰 基础使用 152 | 153 | #### 测试默认端口(80) 154 | ```bash 155 | $ tcping google.com 156 | 正在对 google.com (IPv4 - 142.250.191.14) 端口 80 执行 TCP Ping 157 | 从 142.250.191.14:80 收到响应: seq=0 time=31.45ms 158 | 从 142.250.191.14:80 收到响应: seq=1 time=29.78ms 159 | 从 142.250.191.14:80 收到响应: seq=2 time=30.12ms 160 | ^C 161 | 操作被中断。 162 | 163 | --- 目标主机 TCP ping 统计 --- 164 | 已发送 = 3, 已接收 = 3, 丢失 = 0 (0.0% 丢失) 165 | 往返时间(RTT): 最小 = 29.78ms, 最大 = 31.45ms, 平均 = 30.45ms 166 | ``` 167 | 168 | #### 测试指定端口,例如HTTPS端口(443) 169 | ```bash 170 | $ tcping google.com 443 171 | # 或使用 -p 参数 172 | $ tcping -p 443 google.com 173 | # 或使用 host:port 格式 174 | $ tcping google.com:443 175 | ``` 176 | 177 | ### 🎯 高级用法 178 | 179 | #### 限制测试次数和间隔 180 | ```bash 181 | $ tcping -n 5 -t 2000 example.com 443 182 | 正在对 example.com (IPv4 - 93.184.216.34) 端口 443 执行 TCP Ping 183 | 从 93.184.216.34:443 收到响应: seq=0 time=142.93ms 184 | 从 93.184.216.34:443 收到响应: seq=1 time=138.45ms 185 | 从 93.184.216.34:443 收到响应: seq=2 time=140.12ms 186 | 从 93.184.216.34:443 收到响应: seq=3 time=137.68ms 187 | 从 93.184.216.34:443 收到响应: seq=4 time=139.74ms 188 | 189 | --- 目标主机 TCP ping 统计 --- 190 | 已发送 = 5, 已接收 = 5, 丢失 = 0 (0.0% 丢失) 191 | 往返时间(RTT): 最小 = 137.68ms, 最大 = 142.93ms, 平均 = 139.78ms 192 | ``` 193 | 194 | #### 强制使用IPv6 195 | ```bash 196 | $ tcping -6 ipv6.google.com 443 197 | 正在对 ipv6.google.com (IPv6 - 2404:6800:4003:c04::8b) 端口 443 执行 TCP Ping 198 | 从 2404:6800:4003:c04::8b:443 收到响应: seq=0 time=36.24ms 199 | 从 2404:6800:4003:c04::8b:443 收到响应: seq=1 time=35.87ms 200 | ^C 201 | 操作被中断。 202 | 203 | --- 目标主机 TCP ping 统计 --- 204 | 已发送 = 2, 已接收 = 2, 丢失 = 0 (0.0% 丢失) 205 | 往返时间(RTT): 最小 = 35.87ms, 最大 = 36.24ms, 平均 = 36.06ms 206 | ``` 207 | 208 | #### 彩色输出和详细模式 209 | ```bash 210 | $ tcping -c -v github.com 443 211 | 正在对 github.com (IPv4 - 20.205.243.166) 端口 443 执行 TCP Ping 212 | 域名 github.com 解析到的所有IP地址: 213 | [1] IPv4: 20.205.243.166 214 | [2] IPv4: 20.27.177.113 215 | 使用IP地址: 20.205.243.166 216 | 217 | 从 20.205.243.166:443 收到响应: seq=0 time=138.45ms 218 | 详细信息: 本地地址=192.168.1.100:50123, 远程地址=20.205.243.166:443 219 | 从 20.205.243.166:443 收到响应: seq=1 time=140.12ms 220 | 详细信息: 本地地址=192.168.1.100:50124, 远程地址=20.205.243.166:443 221 | 从 20.205.243.166:443 收到响应: seq=2 time=136.78ms 222 | 详细信息: 本地地址=192.168.1.100:50125, 远程地址=20.205.243.166:443 223 | ^C 224 | 操作被中断。 225 | 226 | --- 目标主机 TCP ping 统计 --- 227 | 已发送 = 3, 已接收 = 3, 丢失 = 0 (0.0% 丢失) 228 | 往返时间(RTT): 最小 = 136.78ms, 最大 = 140.12ms, 平均 = 138.45ms 229 | 抖动(Jitter): 平均 = 1.67ms 230 | ``` 231 | 232 | #### 网络质量分析 233 | ```bash 234 | $ tcping -v -n 10 -c unstable-server.com 80 235 | 正在对 unstable-server.com (IPv4 - 203.0.113.10) 端口 80 执行 TCP Ping 236 | 从 203.0.113.10:80 收到响应: seq=0 time=45.23ms 237 | 从 203.0.113.10:80 收到响应: seq=1 time=52.67ms 238 | 从 203.0.113.10:80 收到响应: seq=2 time=38.91ms 239 | 从 203.0.113.10:80 收到响应: seq=3 time=61.34ms 240 | 从 203.0.113.10:80 收到响应: seq=4 time=44.78ms 241 | 从 203.0.113.10:80 收到响应: seq=5 time=55.12ms 242 | 从 203.0.113.10:80 收到响应: seq=6 time=41.56ms 243 | 从 203.0.113.10:80 收到响应: seq=7 time=49.89ms 244 | 从 203.0.113.10:80 收到响应: seq=8 time=58.23ms 245 | 从 203.0.113.10:80 收到响应: seq=9 time=46.45ms 246 | 247 | --- 目标主机 TCP ping 统计 --- 248 | 已发送 = 10, 已接收 = 10, 丢失 = 0 (0.0% 丢失) 249 | 往返时间(RTT): 最小 = 38.91ms, 最大 = 61.34ms, 平均 = 49.42ms 250 | 抖动(Jitter): 平均 = 8.45ms 251 | ``` 252 | 253 | ### 🔢 直接IP地址测试 254 | 255 | #### 标准IPv4地址 256 | ```bash 257 | $ tcping 8.8.8.8 443 258 | 正在对 8.8.8.8 (IPv4 - 8.8.8.8) 端口 443 执行 TCP Ping 259 | ... 260 | ``` 261 | 262 | #### IPv6地址 263 | ```bash 264 | $ tcping 2001:4860:4860::8888 443 265 | 正在对 2001:4860:4860::8888 (IPv6 - 2001:4860:4860::8888) 端口 443 执行 TCP Ping 266 | ... 267 | ``` 268 | 269 | ### ⚡ 快速诊断 270 | 271 | #### 短超时测试 272 | ```bash 273 | $ tcping -w 100 slow-server.example.com 80 274 | 正在对 slow-server.example.com (IPv4 - 203.0.113.1) 端口 80 执行 TCP Ping 275 | TCP连接失败 203.0.113.1:80: seq=0 错误=连接超时 276 | TCP连接失败 203.0.113.1:80: seq=1 错误=连接超时 277 | ^C 278 | 操作被中断。 279 | 280 | --- 目标主机 TCP ping 统计 --- 281 | 已发送 = 2, 已接收 = 0, 丢失 = 2 (100.0% 丢失) 282 | ``` 283 | 284 | ### 🛠️ 常用场景 285 | 286 | | 使用场景 | 命令示例 | 说明 | 287 | |----------|----------|------| 288 | | 基本连通性测试 | `tcping google.com` | 测试HTTP连通性 | 289 | | HTTPS服务测试 | `tcping -p 443 example.com` | 测试HTTPS服务 | 290 | | SSH服务测试 | `tcping -p 22 server.com` | 测试SSH连接 | 291 | | 数据库连接测试 | `tcping -p 3306 db.server.com` | 测试MySQL连接 | 292 | | 快速诊断 | `tcping -n 3 -w 500 host.com 80` | 3次快速测试 | 293 | | 持续监控 | `tcping -t 5000 -c service.com 443` | 每5秒测试一次 | 294 | | 网络质量分析 | `tcping -v -n 20 target.com 443` | 详细统计含抖动分析 | 295 | | 多IP域名测试 | `tcping -v cdn.example.com 80` | 查看域名所有IP并测试首个IP | 296 | 297 | 298 | 299 | ## 🔍 地址解析逻辑 300 | 301 | TCPing 提供了强大而灵活的地址解析功能: 302 | 303 | ### IPv4 地址解析 304 | | 格式类型 | 示例 | 说明 | 305 | |----------|------|------| 306 | | **标准点分十进制** | `8.8.8.8` | 传统IPv4格式 | 307 | 308 | ### IPv6 地址解析 309 | - 支持标准 IPv6 地址格式(如 `2404:6800:4003:c04::8b`) 310 | - 自动添加方括号用于端口分隔 311 | 312 | ### 域名解析 313 | - 智能DNS解析,支持A和AAAA记录 314 | - 根据 `-4` 或 `-6` 参数强制协议类型 315 | - 自动选择最优可用地址 316 | - 详细模式下显示所有解析到的IP地址 317 | 318 | ### 解析优先级 319 | 1. **直接IP解析**:解析标准IP地址格式 320 | 2. **DNS查询**:进行域名解析,优先选择IPv4地址 321 | 322 | 323 | 324 | ## 📊 网络统计分析 325 | 326 | ### 基础统计信息 327 | TCPing 提供全面的网络连接统计: 328 | - **发送/接收统计**:准确记录请求发送和响应接收数量 329 | - **丢包率计算**:实时计算连接失败率 330 | - **延迟统计**:最小、最大、平均往返时间(RTT) 331 | 332 | ### 网络抖动(Jitter)分析 333 | 在详细模式(`-v`)下,TCPing 会计算网络抖动: 334 | 335 | #### 什么是网络抖动? 336 | 网络抖动是指连续两次测量之间延迟时间的变化,是衡量网络稳定性的重要指标: 337 | - **低抖动**:网络连接稳定,延迟变化小 338 | - **高抖动**:网络不稳定,可能影响实时应用 339 | 340 | #### 抖动计算方法 341 | ``` 342 | 抖动 = |当前RTT - 上一次RTT| 343 | 平均抖动 = 所有抖动值的平均数 344 | ``` 345 | 346 | #### 抖动值参考 347 | | 抖动范围 | 网络质量 | 适用场景 | 348 | |----------|----------|----------| 349 | | < 5ms | 优秀 | 实时游戏、视频通话 | 350 | | 5-20ms | 良好 | 一般网络应用 | 351 | | 20-50ms | 一般 | 文件传输、网页浏览 | 352 | | > 50ms | 较差 | 可能影响用户体验 | 353 | 354 | #### 示例输出 355 | ```bash 356 | $ tcping -v -n 10 example.com 443 357 | ... 358 | --- 目标主机 TCP ping 统计 --- 359 | 已发送 = 10, 已接收 = 10, 丢失 = 0 (0.0% 丢失) 360 | 往返时间(RTT): 最小 = 45.23ms, 最大 = 52.67ms, 平均 = 48.45ms 361 | 抖动(Jitter): 平均 = 2.34ms 362 | ``` 363 | 364 | ## ⚠️ 错误处理 365 | 366 | TCPing 提供了全面的错误处理机制: 367 | 368 | ### 参数验证 369 | - ✅ 端口范围验证(1-65535) 370 | - ✅ 协议冲突检测(-4与-6同时使用) 371 | - ✅ 数值参数合法性检查 372 | 373 | ### 网络错误 374 | - 🔍 **地址解析失败**:详细的DNS错误信息 375 | - ⏱️ **连接超时**:明确的超时提示 376 | - 🚫 **连接被拒绝**:端口关闭或服务不可用 377 | - 📡 **网络不可达**:路由或网络配置问题 378 | 379 | ### 用户友好提示 380 | - 彩色错误输出(启用 `-c` 选项时) 381 | - 详细的错误描述和可能的解决建议 382 | - 完整的统计信息,包括失败次数和丢包率 383 | - 详细模式下提供网络抖动分析,帮助诊断网络稳定性 384 | - 智能域名解析显示,展示所有可用IP地址 385 | 386 | 387 | 388 | ## ❓ 常见问题 389 | 390 | ### 🤔 基础概念 391 | 392 | **Q: 为什么使用TCPing而不是普通的ping?** 393 | > **A:** 普通ping使用ICMP协议,在某些网络环境下可能被防火墙阻止。TCPing使用TCP协议测试特定端口,能够: 394 | > - 测试具体服务的可用性(如HTTP、HTTPS、SSH等) 395 | > - 绕过ICMP阻止策略 396 | > - 提供更准确的应用层连通性测试 397 | 398 | ### 🌐 网络相关 399 | 400 | **Q: 为什么有些域名无法进行IPv6测试?** 401 | > **A:** 可能的原因: 402 | > - 域名未配置AAAA记录(IPv6 DNS记录) 403 | > - 网络不支持IPv6连接 404 | > - DNS服务器不支持IPv6解析 405 | > 406 | > **解决方案**:使用 `nslookup -type=AAAA domain.com` 检查IPv6记录 407 | 408 | **Q: 测试结果显示连接成功,但服务实际不可用?** 409 | > **A:** TCPing只测试TCP连接建立,不验证应用层协议。连接成功表示: 410 | > - 目标端口已开放 411 | > - 网络路径畅通 412 | > - 但具体服务可能存在应用层问题 413 | 414 | ### 🎨 显示相关 415 | 416 | **Q: 彩色输出在某些终端不起作用?** 417 | > **A:** 解决方案: 418 | > - **Windows**: 使用Windows Terminal或PowerShell 7+ 419 | > - **旧版CMD**: 不支持ANSI颜色,建议升级为`终端`(`Terminal`) 420 | > - **Linux/macOS**: 确保终端支持ANSI转义序列 421 | 422 | ### 📊 性能相关 423 | 424 | **Q: 高负载网络下测试结果不准确?** 425 | > **A:** 建议: 426 | > - 增加测试次数:`tcping -n 10 target.com` 427 | > - 适当增加间隔:`tcping -t 2000 target.com` 428 | > - 关注统计结果而非单次测试值 429 | > - 在不同时间段进行多次测试 430 | > - 使用详细模式查看抖动信息:`tcping -v target.com` 431 | 432 | **Q: 网络抖动值多少算正常?** 433 | > **A:** 抖动值参考: 434 | > - **< 5ms**: 网络质量优秀,适合实时应用 435 | > - **5-20ms**: 网络质量良好,一般应用无问题 436 | > - **20-50ms**: 网络质量一般,可能影响实时性要求高的应用 437 | > - **> 50ms**: 网络不稳定,建议检查网络配置 438 | > 439 | > **注意**: 抖动值只在详细模式(`-v`)下显示 440 | 441 | **Q: 为什么延迟很低但抖动很高?** 442 | > **A:** 可能原因: 443 | > - 网络路径不稳定(路由切换) 444 | > - 网络设备负载波动 445 | > - ISP网络质量问题 446 | > - 本地网络环境干扰 447 | > 448 | > **建议**: 在不同时间段多次测试,观察抖动变化趋势 449 | 450 | ### 🔧 技术问题 451 | 452 | **Q: 如何测试特定本地IP绑定?** 453 | > **A:** TCPing会自动选择最佳本地IP,若需指定,可考虑: 454 | > - 配置路由表 455 | > - 使用网络命名空间(Linux) 456 | > - 临时禁用其他网络接口 457 | 458 | **Q: 支持测试UDP端口吗?** 459 | > **A:** 当前版本仅支持TCP连接测试。UDP测试需要不同的实现机制,可能在未来版本中添加。 460 | 461 | ## 🛠️ 自行编译 462 | 463 | ### 环境要求 464 | - Go 1.24+ 465 | - Git 466 | 467 | ### 快速编译 468 | ```bash 469 | # 克隆仓库 470 | git clone https://github.com/nodeseeker/tcping.git 471 | cd tcping 472 | 473 | # 编译当前平台版本 474 | go build -o tcping src/main.go 475 | 476 | # 编译优化版本(推荐) 477 | CGO_ENABLED=0 go build -trimpath -ldflags="-w -s" -o tcping src/main.go 478 | ``` 479 | 480 | ### 交叉编译 481 | ```bash 482 | # Linux amd64 483 | CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-w -s" -o tcping-linux-amd64 src/main.go 484 | 485 | # Windows amd64 486 | CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -trimpath -ldflags="-w -s" -o tcping-windows-amd64.exe src/main.go 487 | 488 | # macOS arm64 489 | CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -trimpath -ldflags="-w -s" -o tcping-darwin-arm64 src/main.go 490 | ``` 491 | 492 | ### 批量编译 493 | 项目提供了 `compiler.sh` 脚本,支持一键编译所有平台版本: 494 | 495 | ```bash 496 | chmod +x compiler.sh 497 | ./compiler.sh 498 | ``` 499 | 500 | 编译产物将输出到 `./bin` 目录,并自动生成SHA256校验文件。 501 | 502 | ### 功能测试 503 | 项目提供了 `test.sh` 脚本用于验证编译后的程序功能: 504 | 505 | ```bash 506 | chmod +x test.sh 507 | ./test.sh 508 | ``` 509 | 510 | 测试脚本会验证IPv4、IPv6和域名解析等核心功能。 511 | 512 | ### 编译参数说明 513 | - `CGO_ENABLED=0`: 禁用CGO,确保静态链接 514 | - `-trimpath`: 移除路径信息,减小文件大小 515 | - `-ldflags="-w -s"`: 移除调试信息和符号表 516 | - `-o`: 指定输出文件名 517 | 518 | 519 | ## 📄 许可证 520 | 521 | 本项目采用 [GPL-3.0](https://www.gnu.org/licenses/gpl-3.0.html) 开源许可证。 522 | 523 | 524 | ### 👥 贡献者 525 | 526 | 感谢所有为项目做出贡献的开发者! 527 | 528 | 529 | 530 | 531 | 532 | --- 533 | 534 | 535 |
536 | 537 | **🌟 如果TCPing对您有帮助,请给我们一个Star!** 538 | 539 | Made with ❤️ by [nodeseeker](https://github.com/nodeseeker) 540 | 541 |
542 | -------------------------------------------------------------------------------- /install_cn.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # tcping 安装/更新/卸载脚本 (国内版本) 4 | # 用于自动安装、更新或卸载 tcping 工具 5 | # 支持架构:amd64, arm64, 386, arm, loong64 6 | # 国内版本:优先使用国内镜像源,提高下载速度 7 | # 8 | # 使用方法: 9 | # sudo ./install_cn.sh # 安装或更新 tcping 10 | # sudo ./install_cn.sh -u # 卸载 tcping 11 | # sudo ./install_cn.sh -f # 强制安装(跳过确认) 12 | # sudo ./install_cn.sh -v # 详细输出 13 | # 14 | 15 | set -euo pipefail # 严格模式:遇到错误立即退出,未定义变量报错,管道错误传播 16 | 17 | # 颜色定义 18 | readonly RED='\033[0;31m' 19 | readonly GREEN='\033[0;32m' 20 | readonly YELLOW='\033[1;33m' 21 | readonly BLUE='\033[0;34m' 22 | readonly CYAN='\033[0;36m' 23 | readonly BOLD='\033[1m' 24 | readonly NC='\033[0m' # No Color 25 | 26 | # 基本配置 27 | readonly INSTALL_DIR="/usr/local/bin" 28 | readonly TCPING_BIN="tcping" 29 | readonly GITHUB_API="https://api.github.com/repos/nodeseeker/tcping" 30 | readonly GITHUB_REPO="nodeseeker/tcping" 31 | readonly TEMP_DIR="/tmp/tcping_install" 32 | 33 | # 国内镜像源配置(按优先级排序) 34 | readonly MIRROR_SOURCES=( 35 | "https://gh-proxy.com/https://github.com" 36 | "https://ghfast.top/https://github.com" 37 | "https://github.com" 38 | ) 39 | 40 | # 全局变量 41 | VERBOSE=false 42 | FORCE=false 43 | UNINSTALL=false 44 | CURRENT_VERSION="" 45 | LATEST_VERSION="" 46 | 47 | # 打印函数 48 | print_info() { 49 | echo -e "${BLUE}[INFO]${NC} $1" 50 | } 51 | 52 | print_success() { 53 | echo -e "${GREEN}[SUCCESS]${NC} $1" 54 | } 55 | 56 | print_warning() { 57 | echo -e "${YELLOW}[WARNING]${NC} $1" 58 | } 59 | 60 | print_error() { 61 | echo -e "${RED}[ERROR]${NC} $1" >&2 62 | } 63 | 64 | print_verbose() { 65 | if [[ "$VERBOSE" == true ]]; then 66 | echo -e "${CYAN}[VERBOSE]${NC} $1" 67 | fi 68 | } 69 | 70 | print_title() { 71 | echo -e "${BOLD}${BLUE}$1${NC}" 72 | } 73 | 74 | # 显示帮助信息 75 | show_help() { 76 | cat << EOF 77 | TCPing 安装脚本 (国内版本) 78 | 79 | 用法: $0 [选项] 80 | 81 | 选项: 82 | -u, --uninstall 卸载 tcping 83 | -f, --force 强制安装(跳过确认) 84 | -v, --verbose 详细输出 85 | -h, --help 显示此帮助信息 86 | 87 | 支持的架构: amd64, arm64, 386, arm, loong64 88 | 89 | 国内版本特性: 90 | - 优先使用国内镜像源 (gh-proxy.com, ghfast.top) 91 | - 自动回退到 GitHub 原始地址 92 | - 提高下载速度和成功率 93 | 94 | 示例: 95 | sudo $0 # 安装或更新 tcping 96 | sudo $0 -u # 卸载 tcping 97 | sudo $0 -f # 强制安装 98 | sudo $0 -v # 详细输出安装过程 99 | 100 | EOF 101 | } 102 | 103 | # 检查 root 权限 104 | check_root() { 105 | if [[ $EUID -ne 0 ]]; then 106 | print_error "此脚本需要 root 权限运行" 107 | print_info "请使用: sudo $0" 108 | exit 1 109 | fi 110 | print_verbose "Root 权限检查通过" 111 | } 112 | 113 | # 检查系统依赖 114 | check_dependencies() { 115 | local missing_deps=() 116 | local deps=("curl" "unzip" "grep" "awk") 117 | 118 | print_verbose "检查系统依赖..." 119 | 120 | for dep in "${deps[@]}"; do 121 | if ! command -v "$dep" &> /dev/null; then 122 | missing_deps+=("$dep") 123 | fi 124 | done 125 | 126 | if [[ ${#missing_deps[@]} -gt 0 ]]; then 127 | print_warning "缺少以下依赖程序: ${missing_deps[*]}" 128 | echo -n "是否安装缺少的依赖? [y/N]: " 129 | 130 | if [[ "$FORCE" == true ]]; then 131 | echo "y (强制模式)" 132 | install_dependencies "${missing_deps[@]}" 133 | else 134 | read -r response 135 | if [[ "$response" =~ ^[Yy]$ ]]; then 136 | install_dependencies "${missing_deps[@]}" 137 | else 138 | print_error "缺少必要依赖,无法继续安装" 139 | exit 1 140 | fi 141 | fi 142 | else 143 | print_verbose "所有依赖已满足" 144 | fi 145 | } 146 | 147 | # 安装依赖 148 | install_dependencies() { 149 | local deps=("$@") 150 | print_info "正在安装依赖: ${deps[*]}" 151 | 152 | if command -v apt &> /dev/null; then 153 | apt update && apt install -y "${deps[@]}" 154 | elif command -v yum &> /dev/null; then 155 | yum install -y "${deps[@]}" 156 | elif command -v dnf &> /dev/null; then 157 | dnf install -y "${deps[@]}" 158 | elif command -v pacman &> /dev/null; then 159 | pacman -S --noconfirm "${deps[@]}" 160 | elif command -v apk &> /dev/null; then 161 | apk add "${deps[@]}" 162 | elif command -v zypper &> /dev/null; then 163 | zypper install -y "${deps[@]}" 164 | else 165 | print_error "无法识别的包管理器,请手动安装: ${deps[*]}" 166 | exit 1 167 | fi 168 | 169 | print_success "依赖安装完成" 170 | } 171 | 172 | # 获取系统架构 173 | get_arch() { 174 | local arch 175 | arch=$(uname -m) 176 | 177 | case "$arch" in 178 | x86_64|amd64) 179 | echo "amd64" 180 | ;; 181 | aarch64|arm64) 182 | echo "arm64" 183 | ;; 184 | i386|i686) 185 | echo "386" 186 | ;; 187 | armv6l|armv7l|arm*) 188 | echo "arm" 189 | ;; 190 | loongarch64) 191 | echo "loong64" 192 | ;; 193 | *) 194 | print_error "不支持的架构: $arch" 195 | print_info "支持的架构: amd64, arm64, 386, arm, loong64" 196 | exit 1 197 | ;; 198 | esac 199 | } 200 | 201 | # 获取当前已安装版本 202 | get_current_version() { 203 | if command -v "$TCPING_BIN" &> /dev/null; then 204 | # 执行 tcping --version 并解析版本号 205 | local version_output 206 | version_output=$("$TCPING_BIN" --version 2>/dev/null || echo "") 207 | if [[ -n "$version_output" ]]; then 208 | # 提取版本号,格式类似 "TCPing 版本 v1.7.1" 209 | CURRENT_VERSION=$(echo "$version_output" | grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' | head -1) 210 | fi 211 | fi 212 | 213 | if [[ -n "$CURRENT_VERSION" ]]; then 214 | print_verbose "当前安装版本: $CURRENT_VERSION" 215 | else 216 | print_verbose "未检测到已安装的 tcping" 217 | fi 218 | } 219 | 220 | # 获取最新版本 221 | get_latest_version() { 222 | print_verbose "正在获取最新版本信息..." 223 | 224 | local api_response 225 | api_response=$(curl -s "$GITHUB_API/releases/latest" 2>/dev/null || echo "") 226 | 227 | if [[ -n "$api_response" ]]; then 228 | LATEST_VERSION=$(echo "$api_response" | grep -oE '"tag_name":\s*"[^"]*"' | cut -d'"' -f4) 229 | fi 230 | 231 | if [[ -z "$LATEST_VERSION" ]]; then 232 | print_warning "无法获取最新版本信息,使用默认版本 v1.7.1" 233 | LATEST_VERSION="v1.7.1" 234 | fi 235 | 236 | print_verbose "最新版本: $LATEST_VERSION" 237 | } 238 | 239 | # 比较版本 240 | compare_versions() { 241 | local current="$1" 242 | local latest="$2" 243 | 244 | # 移除 v 前缀 245 | current=${current#v} 246 | latest=${latest#v} 247 | 248 | # 使用 sort 比较版本号 249 | local higher 250 | higher=$(printf '%s\n%s\n' "$current" "$latest" | sort -V | tail -n1) 251 | 252 | if [[ "$higher" == "$latest" && "$current" != "$latest" ]]; then 253 | return 1 # 需要更新 254 | else 255 | return 0 # 已是最新或更高版本 256 | fi 257 | } 258 | 259 | # 尝试从指定源下载文件 260 | try_download() { 261 | local download_url="$1" 262 | local output_file="$2" 263 | local timeout=30 264 | 265 | print_verbose "尝试从源下载: $download_url" 266 | 267 | # 使用 curl 下载,设置超时和重试 268 | if curl -L --connect-timeout 10 --max-time $timeout --retry 2 -o "$output_file" "$download_url" 2>/dev/null; then 269 | # 验证下载的文件是否为有效的zip文件 270 | if unzip -t "$output_file" &>/dev/null; then 271 | print_verbose "下载成功: $(basename "$download_url")" 272 | return 0 273 | else 274 | print_verbose "下载的文件损坏,删除并重试" 275 | rm -f "$output_file" 276 | return 1 277 | fi 278 | else 279 | print_verbose "下载失败: $(basename "$download_url")" 280 | rm -f "$output_file" 281 | return 1 282 | fi 283 | } 284 | 285 | # 下载并安装 tcping 286 | install_tcping() { 287 | local arch 288 | arch=$(get_arch) 289 | 290 | print_info "正在为 $arch 架构下载 tcping $LATEST_VERSION..." 291 | print_info "使用国内镜像源加速下载..." 292 | 293 | # 创建临时目录 294 | mkdir -p "$TEMP_DIR" 295 | cd "$TEMP_DIR" 296 | 297 | # 构造文件名 298 | local filename="tcping-linux-$arch" 299 | local output_file="tcping.zip" 300 | local download_success=false 301 | 302 | # 尝试从各个镜像源下载 303 | for mirror in "${MIRROR_SOURCES[@]}"; do 304 | local download_url="$mirror/$GITHUB_REPO/releases/download/$LATEST_VERSION/${filename}.zip" 305 | 306 | print_info "正在尝试镜像源: $(echo "$mirror" | cut -d'/' -f3)" 307 | 308 | if try_download "$download_url" "$output_file"; then 309 | download_success=true 310 | print_success "下载成功!使用的镜像源: $(echo "$mirror" | cut -d'/' -f3)" 311 | break 312 | else 313 | print_warning "镜像源 $(echo "$mirror" | cut -d'/' -f3) 下载失败,尝试下一个源..." 314 | fi 315 | 316 | # 等待一秒再尝试下一个源 317 | sleep 1 318 | done 319 | 320 | if [[ "$download_success" != true ]]; then 321 | print_error "所有镜像源下载均失败" 322 | print_info "可能的原因:" 323 | print_info "1. 网络连接问题" 324 | print_info "2. 版本 $LATEST_VERSION 不存在" 325 | print_info "3. 架构 $arch 不受支持" 326 | cleanup 327 | exit 1 328 | fi 329 | 330 | # 解压文件 331 | print_verbose "正在解压文件..." 332 | if ! unzip -q "$output_file"; then 333 | print_error "解压失败" 334 | cleanup 335 | exit 1 336 | fi 337 | 338 | # 查找二进制文件 339 | local binary_file 340 | binary_file=$(find . -name "$TCPING_BIN" -type f | head -1) 341 | 342 | if [[ -z "$binary_file" ]]; then 343 | print_error "未找到二进制文件" 344 | cleanup 345 | exit 1 346 | fi 347 | 348 | # 安装二进制文件 349 | print_verbose "正在安装到 $INSTALL_DIR/$TCPING_BIN..." 350 | if ! cp "$binary_file" "$INSTALL_DIR/$TCPING_BIN"; then 351 | print_error "安装失败:无法复制文件到 $INSTALL_DIR" 352 | cleanup 353 | exit 1 354 | fi 355 | 356 | # 设置执行权限 357 | chmod +x "$INSTALL_DIR/$TCPING_BIN" 358 | 359 | # 清理临时文件 360 | cleanup 361 | 362 | print_success "tcping $LATEST_VERSION 安装完成!" 363 | 364 | # 验证安装 365 | if command -v "$TCPING_BIN" &> /dev/null; then 366 | print_info "安装验证:" 367 | "$TCPING_BIN" --version 368 | else 369 | print_warning "安装完成,但 $TCPING_BIN 不在 PATH 中" 370 | print_info "请确保 $INSTALL_DIR 在您的 PATH 环境变量中" 371 | fi 372 | } 373 | 374 | # 卸载 tcping 375 | uninstall_tcping() { 376 | if [[ -f "$INSTALL_DIR/$TCPING_BIN" ]]; then 377 | print_info "正在卸载 tcping..." 378 | 379 | if [[ "$FORCE" == false ]]; then 380 | echo -n "确认卸载 tcping? [y/N]: " 381 | read -r response 382 | if [[ ! "$response" =~ ^[Yy]$ ]]; then 383 | print_info "取消卸载" 384 | exit 0 385 | fi 386 | fi 387 | 388 | rm -f "$INSTALL_DIR/$TCPING_BIN" 389 | print_success "tcping 已成功卸载" 390 | else 391 | print_warning "tcping 未安装" 392 | fi 393 | } 394 | 395 | # 清理临时文件 396 | cleanup() { 397 | if [[ -d "$TEMP_DIR" ]]; then 398 | rm -rf "$TEMP_DIR" 399 | print_verbose "临时文件已清理" 400 | fi 401 | } 402 | 403 | # 主函数 404 | main() { 405 | # 解析命令行参数 406 | while [[ $# -gt 0 ]]; do 407 | case $1 in 408 | -u|--uninstall) 409 | UNINSTALL=true 410 | shift 411 | ;; 412 | -f|--force) 413 | FORCE=true 414 | shift 415 | ;; 416 | -v|--verbose) 417 | VERBOSE=true 418 | shift 419 | ;; 420 | -h|--help) 421 | show_help 422 | exit 0 423 | ;; 424 | *) 425 | print_error "未知选项: $1" 426 | show_help 427 | exit 1 428 | ;; 429 | esac 430 | done 431 | 432 | # 显示标题 433 | print_title "TCPing 安装脚本 (国内版本)" 434 | echo 435 | 436 | # 检查权限 437 | check_root 438 | 439 | # 如果是卸载模式 440 | if [[ "$UNINSTALL" == true ]]; then 441 | uninstall_tcping 442 | exit 0 443 | fi 444 | 445 | # 检查依赖 446 | check_dependencies 447 | 448 | # 获取版本信息 449 | get_current_version 450 | get_latest_version 451 | 452 | # 检查是否需要安装或更新 453 | if [[ -z "$CURRENT_VERSION" ]]; then 454 | print_info "检测到 tcping 未安装" 455 | 456 | if [[ "$FORCE" == false ]]; then 457 | echo -n "是否安装 tcping $LATEST_VERSION? [Y/n]: " 458 | read -r response 459 | if [[ "$response" =~ ^[Nn]$ ]]; then 460 | print_info "取消安装" 461 | exit 0 462 | fi 463 | fi 464 | 465 | install_tcping 466 | else 467 | print_info "检测到已安装版本: $CURRENT_VERSION" 468 | 469 | if compare_versions "$CURRENT_VERSION" "$LATEST_VERSION"; then 470 | print_success "您已安装最新版本 $CURRENT_VERSION" 471 | 472 | if [[ "$FORCE" == true ]]; then 473 | print_info "强制重新安装..." 474 | install_tcping 475 | fi 476 | else 477 | print_info "发现新版本: $LATEST_VERSION" 478 | 479 | if [[ "$FORCE" == false ]]; then 480 | echo -n "是否更新到 $LATEST_VERSION? [Y/n]: " 481 | read -r response 482 | if [[ "$response" =~ ^[Nn]$ ]]; then 483 | print_info "取消更新" 484 | exit 0 485 | fi 486 | fi 487 | 488 | install_tcping 489 | fi 490 | fi 491 | } 492 | 493 | # 设置清理陷阱 494 | trap cleanup EXIT INT TERM 495 | 496 | # 运行主函数 497 | main "$@" 498 | -------------------------------------------------------------------------------- /src/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "flag" 7 | "fmt" 8 | "net" 9 | "os" 10 | "os/signal" 11 | "strconv" 12 | "strings" 13 | "sync" 14 | "syscall" 15 | "time" 16 | ) 17 | 18 | const ( 19 | version = "v1.8.0" 20 | copyright = "Copyright (c) 2025. All rights reserved." 21 | programName = "TCPing" 22 | ) 23 | 24 | type Statistics struct { 25 | sync.Mutex 26 | sentCount int64 27 | respondedCount int64 28 | minTime float64 29 | maxTime float64 30 | totalTime float64 31 | lastTime float64 // 上一次的响应时间,用于计算抖动 32 | totalJitter float64 // 总抖动时间 33 | jitterCount int64 // 抖动样本数量 34 | } 35 | 36 | func (s *Statistics) update(elapsed float64, success bool) { 37 | s.Lock() 38 | defer s.Unlock() 39 | 40 | s.sentCount++ 41 | 42 | if !success { 43 | return 44 | } 45 | 46 | s.respondedCount++ 47 | s.totalTime += elapsed 48 | 49 | // 首次响应特殊处理 50 | if s.respondedCount == 1 { 51 | s.minTime = elapsed 52 | s.maxTime = elapsed 53 | s.lastTime = elapsed 54 | return 55 | } 56 | 57 | // 计算抖动 (当前时间与上一次时间的差值的绝对值) 58 | if s.respondedCount > 1 { 59 | jitter := elapsed - s.lastTime 60 | if jitter < 0 { 61 | jitter = -jitter 62 | } 63 | s.totalJitter += jitter 64 | s.jitterCount++ 65 | } 66 | s.lastTime = elapsed 67 | 68 | // 更新最小和最大时间 69 | if elapsed < s.minTime { 70 | s.minTime = elapsed 71 | } 72 | if elapsed > s.maxTime { 73 | s.maxTime = elapsed 74 | } 75 | } 76 | 77 | func (s *Statistics) getStats() (sent, responded int64, min, max, avg float64) { 78 | s.Lock() 79 | defer s.Unlock() 80 | 81 | avg = 0.0 82 | if s.respondedCount > 0 { 83 | avg = s.totalTime / float64(s.respondedCount) 84 | } 85 | 86 | return s.sentCount, s.respondedCount, s.minTime, s.maxTime, avg 87 | } 88 | 89 | func (s *Statistics) getJitter() float64 { 90 | s.Lock() 91 | defer s.Unlock() 92 | 93 | if s.jitterCount > 0 { 94 | return s.totalJitter / float64(s.jitterCount) 95 | } 96 | return 0.0 97 | } 98 | 99 | type Options struct { 100 | UseIPv4 bool 101 | UseIPv6 bool 102 | Count int 103 | Interval int // 请求间隔(毫秒) 104 | Timeout int 105 | ColorOutput bool 106 | VerboseMode bool 107 | ShowVersion bool 108 | ShowHelp bool 109 | Port int 110 | } 111 | 112 | func handleError(err error, exitCode int) { 113 | if err != nil { 114 | fmt.Fprintf(os.Stderr, "错误: %v\n", err) 115 | os.Exit(exitCode) 116 | } 117 | } 118 | 119 | func printHelp() { 120 | fmt.Printf(`%s %s - TCP 连接测试工具 121 | 122 | 描述: 123 | %s 测试到目标主机和端口的TCP连接性。 124 | 125 | 用法: 126 | tcping [选项] <主机> [端口] (默认端口: 80) 127 | 128 | 选项: 129 | -4, --ipv4 强制使用 IPv4 130 | -6, --ipv6 强制使用 IPv6 131 | -n, --count <次数> 发送请求的次数 (默认: 无限) 132 | -p, --port <端口> 指定要连接的端口 (默认: 80) 133 | -t, --interval <毫秒> 请求间隔 (默认: 1000毫秒) 134 | -w, --timeout <毫秒> 连接超时 (默认: 1000毫秒) 135 | -c, --color 启用彩色输出 136 | -v, --verbose 启用详细模式,显示更多连接信息 137 | -V, --version 显示版本信息 138 | -h, --help 显示此帮助信息 139 | 140 | 示例: 141 | tcping google.com # 基本用法 (默认端口 80) 142 | tcping google.com 443 # 基本用法指定端口 143 | tcping google.com:443 # 使用 host:port 格式 144 | tcping -p 443 google.com # 使用 -p 参数指定端口 145 | tcping -4 -n 5 8.8.8.8 443 # IPv4, 5次请求 146 | tcping -w 2000 example.com 22 # 2秒超时 147 | tcping -c -v example.com 443 # 彩色输出和详细模式 148 | 149 | `, programName, version, programName) 150 | } 151 | 152 | func printVersion() { 153 | fmt.Printf("%s 版本 %s\n", programName, version) 154 | fmt.Println(copyright) 155 | } 156 | 157 | func resolveAddress(address string, useIPv4, useIPv6 bool) (string, []net.IP, error) { 158 | // 尝试标准IP解析 159 | if ip := net.ParseIP(address); ip != nil { 160 | isV4 := ip.To4() != nil 161 | if useIPv4 && !isV4 { 162 | return "", nil, fmt.Errorf("地址 %s 不是 IPv4 地址", address) 163 | } 164 | if useIPv6 && isV4 { 165 | return "", nil, fmt.Errorf("地址 %s 不是 IPv6 地址", address) 166 | } 167 | // 直接输入的IP地址,返回单个IP列表 168 | var ipList []net.IP 169 | ipList = append(ipList, ip) 170 | if !isV4 { 171 | return "[" + ip.String() + "]", ipList, nil 172 | } 173 | return ip.String(), ipList, nil 174 | } 175 | 176 | // 最后尝试DNS解析 177 | ipList, err := net.LookupIP(address) 178 | if err != nil { 179 | return "", nil, fmt.Errorf("解析 %s 失败: %v", address, err) 180 | } 181 | 182 | if len(ipList) == 0 { 183 | return "", nil, fmt.Errorf("未找到 %s 的 IP 地址", address) 184 | } 185 | 186 | if useIPv4 { 187 | for _, ip := range ipList { 188 | if ip.To4() != nil { 189 | return ip.String(), ipList, nil 190 | } 191 | } 192 | return "", ipList, fmt.Errorf("未找到 %s 的 IPv4 地址", address) 193 | } 194 | 195 | if useIPv6 { 196 | for _, ip := range ipList { 197 | if ip.To4() == nil { 198 | return "[" + ip.String() + "]", ipList, nil 199 | } 200 | } 201 | return "", ipList, fmt.Errorf("未找到 %s 的 IPv6 地址", address) 202 | } 203 | 204 | // 如果没有强制指定IP版本,优先使用IPv4地址 205 | // 首先查找IPv4地址 206 | for _, ip := range ipList { 207 | if ip.To4() != nil { 208 | return ip.String(), ipList, nil 209 | } 210 | } 211 | 212 | // 如果没有找到IPv4地址,使用第一个IPv6地址 213 | for _, ip := range ipList { 214 | if ip.To4() == nil { 215 | return "[" + ip.String() + "]", ipList, nil 216 | } 217 | } 218 | 219 | // 理论上不应该到达这里,因为ipList不为空 220 | ip := ipList[0] 221 | if ip.To4() == nil { 222 | return "[" + ip.String() + "]", ipList, nil 223 | } 224 | return ip.String(), ipList, nil 225 | } 226 | 227 | // parseHostPort 解析 host:port 格式的地址 228 | func parseHostPort(input string) (host string, port string, hasPort bool) { 229 | // 检查是否是 IPv6 地址格式 [host]:port 230 | if strings.HasPrefix(input, "[") { 231 | if idx := strings.LastIndex(input, "]:"); idx != -1 { 232 | return input[1:idx], input[idx+2:], true 233 | } 234 | // 纯 IPv6 地址 [host] 235 | if strings.HasSuffix(input, "]") { 236 | return input[1 : len(input)-1], "", false 237 | } 238 | return input, "", false 239 | } 240 | 241 | // 检查是否是 host:port 格式(非 IPv6) 242 | if idx := strings.LastIndex(input, ":"); idx != -1 { 243 | // 确保不是 IPv6 地址(IPv6 有多个冒号) 244 | if strings.Count(input, ":") == 1 { 245 | return input[:idx], input[idx+1:], true 246 | } 247 | } 248 | 249 | return input, "", false 250 | } 251 | 252 | func pingOnce(ctx context.Context, address, port string, timeout int, stats *Statistics, seq int, ip string, 253 | opts *Options) { 254 | // 创建可取消的连接上下文,继承父上下文 255 | dialCtx, dialCancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Millisecond) 256 | defer dialCancel() 257 | 258 | start := time.Now() 259 | var d net.Dialer 260 | conn, err := d.DialContext(dialCtx, "tcp", address+":"+port) 261 | elapsed := float64(time.Since(start).Microseconds()) / 1000.0 262 | 263 | // 检查是否因为主上下文取消而失败 264 | if ctx.Err() == context.Canceled { 265 | msg := "\n操作被中断, 连接尝试已中止\n" 266 | fmt.Print(infoText(msg, opts.ColorOutput)) 267 | return 268 | } 269 | 270 | success := err == nil 271 | stats.update(elapsed, success) 272 | 273 | if !success { 274 | msg := fmt.Sprintf("TCP连接失败 %s:%s: seq=%d 错误=%v\n", ip, port, seq, err) 275 | fmt.Print(errorText(msg, opts.ColorOutput)) 276 | 277 | if opts.VerboseMode { 278 | fmt.Printf(" 详细信息: 连接尝试耗时 %.2fms, 目标 %s:%s\n", elapsed, address, port) 279 | } 280 | return 281 | } 282 | 283 | // 确保连接被关闭 284 | defer conn.Close() 285 | msg := fmt.Sprintf("从 %s:%s 收到响应: seq=%d time=%.2fms\n", ip, port, seq, elapsed) 286 | fmt.Print(successText(msg, opts.ColorOutput)) 287 | 288 | if opts.VerboseMode { 289 | localAddr := conn.LocalAddr().String() 290 | fmt.Printf(" 详细信息: 本地地址=%s, 远程地址=%s:%s\n", localAddr, ip, port) 291 | } 292 | } 293 | 294 | func printTCPingStatistics(stats *Statistics, opts *Options, host, port string) { 295 | sent, responded, min, max, avg := stats.getStats() 296 | 297 | fmt.Printf("\n\n--- 目标 %s 端口 %s 的 TCP ping 统计 ---\n", host, port) 298 | 299 | if sent > 0 { 300 | lossRate := float64(sent-responded) / float64(sent) * 100 301 | fmt.Printf("已发送 = %d, 已接收 = %d, 丢失 = %d (%.1f%% 丢失)\n", 302 | sent, responded, sent-responded, lossRate) 303 | 304 | if responded > 0 { 305 | fmt.Printf("往返时间(RTT): 最小 = %.2fms, 最大 = %.2fms, 平均 = %.2fms\n", 306 | min, max, avg) 307 | 308 | // 在详细模式下显示抖动信息 309 | if opts.VerboseMode { 310 | jitter := stats.getJitter() 311 | fmt.Printf("抖动(Jitter): 平均 = %.2fms\n", jitter) 312 | } 313 | } 314 | } 315 | } 316 | 317 | func colorText(text, colorCode string, useColor bool) string { 318 | if !useColor { 319 | return text 320 | } 321 | return "\033[" + colorCode + "m" + text + "\033[0m" 322 | } 323 | 324 | func successText(text string, useColor bool) string { 325 | return colorText(text, "32", useColor) // 绿色 326 | } 327 | 328 | func errorText(text string, useColor bool) string { 329 | return colorText(text, "31", useColor) // 红色 330 | } 331 | 332 | func infoText(text string, useColor bool) string { 333 | return colorText(text, "36", useColor) // 青色 334 | } 335 | 336 | func setupFlags(opts *Options) { 337 | // 自定义 Usage 函数,使用我们自己的帮助信息 338 | flag.Usage = func() { 339 | printHelp() 340 | } 341 | 342 | // 定义命令行标志,同时设置短选项和长选项 343 | flag.BoolVar(&opts.UseIPv4, "4", false, "") 344 | flag.BoolVar(&opts.UseIPv4, "ipv4", false, "") 345 | flag.BoolVar(&opts.UseIPv6, "6", false, "") 346 | flag.BoolVar(&opts.UseIPv6, "ipv6", false, "") 347 | flag.IntVar(&opts.Count, "n", 0, "") 348 | flag.IntVar(&opts.Count, "count", 0, "") 349 | flag.IntVar(&opts.Interval, "t", 1000, "") 350 | flag.IntVar(&opts.Interval, "interval", 1000, "") 351 | flag.IntVar(&opts.Timeout, "w", 1000, "") 352 | flag.IntVar(&opts.Timeout, "timeout", 1000, "") 353 | flag.IntVar(&opts.Port, "p", 0, "") 354 | flag.IntVar(&opts.Port, "port", 0, "") 355 | flag.BoolVar(&opts.ColorOutput, "c", false, "") 356 | flag.BoolVar(&opts.ColorOutput, "color", false, "") 357 | flag.BoolVar(&opts.VerboseMode, "v", false, "") 358 | flag.BoolVar(&opts.VerboseMode, "verbose", false, "") 359 | flag.BoolVar(&opts.ShowVersion, "V", false, "") 360 | flag.BoolVar(&opts.ShowVersion, "version", false, "") 361 | flag.BoolVar(&opts.ShowHelp, "h", false, "") 362 | flag.BoolVar(&opts.ShowHelp, "help", false, "") 363 | 364 | flag.Parse() 365 | } 366 | 367 | // 新增集中的参数验证函数 368 | func validateOptions(opts *Options, args []string) (string, string, error) { 369 | // 手动解析 flag.Args() 中未被 flag 包解析的选项 370 | // Go 的 flag 包在遇到非选项参数后会停止解析 371 | optionsWithValue := map[string]*int{ 372 | "-n": &opts.Count, "--count": &opts.Count, 373 | "-t": &opts.Interval, "--interval": &opts.Interval, 374 | "-w": &opts.Timeout, "--timeout": &opts.Timeout, 375 | "-p": &opts.Port, "--port": &opts.Port, 376 | } 377 | 378 | boolOptions := map[string]*bool{ 379 | "-4": &opts.UseIPv4, "--ipv4": &opts.UseIPv4, 380 | "-6": &opts.UseIPv6, "--ipv6": &opts.UseIPv6, 381 | "-c": &opts.ColorOutput, "--color": &opts.ColorOutput, 382 | "-v": &opts.VerboseMode, "--verbose": &opts.VerboseMode, 383 | "-V": &opts.ShowVersion, "--version": &opts.ShowVersion, 384 | "-h": &opts.ShowHelp, "--help": &opts.ShowHelp, 385 | } 386 | 387 | var positionalArgs []string 388 | for i := 0; i < len(args); i++ { 389 | arg := args[i] 390 | if ptr, ok := optionsWithValue[arg]; ok { 391 | // 带值的选项 392 | if i+1 < len(args) { 393 | if val, err := strconv.Atoi(args[i+1]); err == nil { 394 | *ptr = val 395 | i++ // 跳过值 396 | continue 397 | } 398 | } 399 | } else if ptr, ok := boolOptions[arg]; ok { 400 | // 布尔选项 401 | *ptr = true 402 | continue 403 | } else if !strings.HasPrefix(arg, "-") { 404 | // 位置参数 405 | positionalArgs = append(positionalArgs, arg) 406 | continue 407 | } 408 | // 未知选项,跳过 409 | } 410 | 411 | // 验证基本选项 412 | if opts.UseIPv4 && opts.UseIPv6 { 413 | return "", "", errors.New("无法同时使用 -4 和 -6 标志") 414 | } 415 | 416 | if opts.Interval < 0 { 417 | return "", "", errors.New("间隔时间不能为负值") 418 | } 419 | 420 | if opts.Timeout <= 0 { 421 | return "", "", errors.New("超时时间必须大于 0") 422 | } 423 | 424 | // 验证主机参数 425 | if len(positionalArgs) < 1 { 426 | return "", "", errors.New("需要提供主机参数\n\n用法: tcping [选项] <主机> [端口]\n尝试 'tcping -h' 获取更多信息") 427 | } 428 | 429 | hostInput := positionalArgs[0] 430 | port := "80" // 默认端口为 80 431 | 432 | // 解析 host:port 格式 433 | host, parsedPort, hasPort := parseHostPort(hostInput) 434 | if hasPort { 435 | port = parsedPort 436 | } 437 | 438 | // 优先级:命令行直接指定的端口 > host:port格式 > -p参数指定的端口 > 默认端口80 439 | if len(positionalArgs) > 1 { 440 | port = positionalArgs[1] 441 | } else if !hasPort && opts.Port > 0 { 442 | // 如果通过-p参数指定了端口且命令行没有直接指定端口,则使用-p参数的值 443 | port = strconv.Itoa(opts.Port) 444 | } 445 | 446 | // 验证端口 447 | if portNum, err := strconv.Atoi(port); err != nil { 448 | return "", "", fmt.Errorf("端口号格式无效") 449 | } else if portNum <= 0 || portNum > 65535 { 450 | return "", "", fmt.Errorf("端口号必须在 1 到 65535 之间") 451 | } 452 | 453 | return host, port, nil 454 | } 455 | 456 | func main() { 457 | // 创建选项结构 458 | opts := &Options{} 459 | 460 | // 设置和解析命令行参数 461 | setupFlags(opts) 462 | 463 | // 处理帮助和版本信息选项,这些选项优先级最高 464 | if opts.ShowHelp { 465 | printHelp() 466 | os.Exit(0) 467 | } 468 | 469 | if opts.ShowVersion { 470 | printVersion() 471 | os.Exit(0) 472 | } 473 | 474 | // 集中验证所有参数 475 | host, port, err := validateOptions(opts, flag.Args()) 476 | if err != nil { 477 | handleError(err, 1) 478 | } 479 | 480 | // 确定使用IPv4还是IPv6 481 | useIPv4 := opts.UseIPv4 482 | useIPv6 := opts.UseIPv6 483 | 484 | // 保存原始主机名用于显示 485 | originalHost := host 486 | 487 | // 解析IP地址 488 | address, allIPs, err := resolveAddress(host, useIPv4, useIPv6) 489 | if err != nil { 490 | handleError(err, 1) 491 | } 492 | 493 | // 提取IP地址用于显示 494 | ipType := "IPv4" 495 | ipAddress := address 496 | if strings.HasPrefix(address, "[") && strings.HasSuffix(address, "]") { 497 | ipType = "IPv6" 498 | ipAddress = address[1 : len(address)-1] 499 | } 500 | 501 | // 仅当用户输入的是域名时,显示额外的 [IP类型 - IP] 信息; 502 | // 如果用户输入的是 IP,则不显示该方括号部分。 503 | if net.ParseIP(originalHost) == nil { 504 | fmt.Printf("正在对 %s [%s - %s] 端口 %s 执行 TCP Ping\n", originalHost, ipType, ipAddress, port) 505 | } else { 506 | fmt.Printf("正在对 %s 端口 %s 执行 TCP Ping\n", originalHost, port) 507 | } 508 | 509 | // 在详细模式下显示所有解析到的IP地址 510 | if opts.VerboseMode && len(allIPs) > 1 { 511 | fmt.Printf("域名 %s 解析到的所有IP地址:\n", originalHost) 512 | for i, ip := range allIPs { 513 | if ip.To4() != nil { 514 | fmt.Printf(" [%d] IPv4: %s\n", i+1, ip.String()) 515 | } else { 516 | fmt.Printf(" [%d] IPv6: %s\n", i+1, ip.String()) 517 | } 518 | } 519 | fmt.Printf("使用IP地址: %s\n\n", ipAddress) 520 | } 521 | stats := &Statistics{} 522 | ctx, cancel := context.WithCancel(context.Background()) 523 | defer cancel() 524 | 525 | // 创建信号捕获通道 526 | interrupt := make(chan os.Signal, 1) 527 | signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) 528 | 529 | // 使用 WaitGroup 来确保后台 goroutine 正确退出 530 | var wg sync.WaitGroup 531 | wg.Add(1) 532 | 533 | // 启动ping协程 534 | go func() { 535 | defer wg.Done() 536 | 537 | for i := 0; opts.Count == 0 || i < opts.Count; i++ { 538 | // 检查上下文是否已取消 539 | select { 540 | case <-ctx.Done(): 541 | return 542 | default: 543 | } 544 | 545 | // 执行ping 546 | pingOnce(ctx, address, port, opts.Timeout, stats, i, ipAddress, opts) 547 | 548 | // 检查是否完成所有请求 549 | if opts.Count != 0 && i == opts.Count-1 { 550 | break 551 | } 552 | 553 | // 等待下一次ping的间隔 554 | select { 555 | case <-ctx.Done(): 556 | return 557 | case <-time.After(time.Duration(opts.Interval) * time.Millisecond): 558 | } 559 | } 560 | }() 561 | 562 | // 等待中断信号或完成 563 | done := make(chan struct{}) 564 | go func() { 565 | wg.Wait() 566 | close(done) 567 | }() 568 | 569 | select { 570 | case <-interrupt: 571 | fmt.Printf("\n操作被中断。\n") 572 | cancel() 573 | case <-done: 574 | // 正常完成 575 | } 576 | // 根据输入判断显示格式: 577 | // - 如果用户输入的是域名,则显示 "域名 (IP)" 578 | // - 如果用户输入的是 IP,则只显示 IP 579 | displayHost := ipAddress 580 | if net.ParseIP(originalHost) == nil { 581 | displayHost = fmt.Sprintf("%s [%s]", originalHost, ipAddress) 582 | } 583 | 584 | printTCPingStatistics(stats, opts, displayHost, port) 585 | } 586 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------