基于 SOC 职业分类
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/ffsshhttiikk/opencode-agents-skills --skill tcp-ip命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
正在显示 SKILL.md
| name | tcp-ip |
| description | TCP/IP networking protocols and implementation |
| category | networking |
| difficulty | intermediate |
| tags | ["network","protocol","tcp","ip","sockets"] |
| author | OpenCode Community |
| version | 1 |
| last_updated | 2024-01-15T00:00:00.000Z |
I am TCP/IP, the fundamental communication protocol suite that enables internet and local network connectivity. I encompass the OSI model layers implemented as TCP/IP layers: Link Layer, Internet Layer, Transport Layer, and Application Layer. I provide reliable, ordered, error-checked delivery of data streams through TCP and faster, connectionless delivery through UDP. I handle addressing through IP addresses (IPv4 and IPv6), routing packets across networks, and managing network interfaces. I enable applications to communicate across heterogeneous networks through standardized protocols. I form the backbone of all modern network communication, from web browsing to video streaming to IoT device communication.
TCP (Transmission Control Protocol): Reliable, connection-oriented protocol with flow control, congestion control, and ordered delivery.
UDP (User Datagram Protocol): Connectionless protocol with low latency, suitable for real-time applications.
IP Addressing: IPv4 (32-bit) and IPv6 (128-bit) addresses identifying network interfaces.
Sockets: Endpoints for network communication exposing APIs for TCP/UDP communication.
Ports: 16-bit identifiers distinguishing between multiple services on a single host.
NAT (Network Address Translation): Mapping private addresses to public addresses for internet connectivity.
MTU (Maximum Transmission Unit): Maximum packet size for network transmission.
TCP Three-Way Handshake: SYN, SYN-ACK, ACK sequence establishing connections.
package main
import (
"bufio"
"fmt"
"log"
"net"
"sync"
"time"
)
type TCPClient struct {
conn net.Conn
id string
joined time.Time
}
type TCPServer struct {
addr string
clients map[string]*TCPClient
mutex sync.RWMutex
broadcast chan string
register chan *TCPClient
unregister chan *TCPClient
}
func NewTCPServer(addr string) *TCPServer {
return &TCPServer{
addr: addr,
clients: make(map[string]*TCPClient),
broadcast: make(chan string, 256),
register: make(chan *TCPClient),
unregister: make(chan *TCPClient),
}
}
func (s *TCPServer) Start() error {
listener, err := net.Listen("tcp", s.addr)
if err != nil {
return fmt.Errorf("failed to listen: %w", err)
}
defer listener.Close()
log.Printf("TCP server listening on %s", s.addr)
s.handleMessages()
{
conn, err := listener.Accept()
err != {
log.Printf(, err)
}
s.handleConnection(conn)
}
}
handleConnection(conn net.Conn) {
conn.Close()
reader := bufio.NewReader(conn)
client := &TCPClient{
conn: conn,
id: conn.RemoteAddr().String(),
joined: time.Now(),
}
s.register <- client
log.Printf(, client.id)
s.broadcast <- fmt.Sprintf(, client.id)
{
message, err := reader.ReadString()
err != {
s.unregister <- client
s.broadcast <- fmt.Sprintf(, client.id)
log.Printf(, client.id)
}
message = strings.TrimSpace(message)
formatted := fmt.Sprintf(, client.id, message)
log.Printf(, formatted)
s.broadcast <- formatted
}
}
handleMessages() {
{
{
client := <-s.register:
s.mutex.Lock()
s.clients[client.id] = client
s.mutex.Unlock()
client := <-s.unregister:
s.mutex.Lock()
_, ok := s.clients[client.id]; ok {
(s.clients, client.id)
client.conn.Close()
}
s.mutex.Unlock()
message := <-s.broadcast:
s.mutex.RLock()
_, client := s.clients {
{
c.conn.SetWriteDeadline(time.Now().Add( * time.Second))
_, err := fmt.Fprintln(c.conn, message)
err != {
s.unregister <- c
}
}(client)
}
s.mutex.RUnlock()
}
}
}
GetClientCount() {
s.mutex.RLock()
s.mutex.RUnlock()
(s.clients)
}
import socket
import threading
import time
from typing import Optional
class UDPServer:
def __init__(self, host: str = '0.0.0.0', port: int = 5000):
self.host = host
self.port = port
self.socket: Optional[socket.socket] = None
self.running = False
self.clients: dict[tuple, float] = {}
self.lock = threading.Lock()
def start(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind((self.host, self.port))
self.socket.settimeout(1.0)
self.running = True
print(f"UDP server started on {self.host}:{self.port}")
while self.running:
try:
data, addr = .socket.recvfrom()
threading.Thread(
target=.handle_client,
args=(data, addr),
daemon=
).start()
socket.timeout:
Exception e:
.running:
()
():
message = data.decode()
()
.lock:
.clients[addr] = time.time()
message.startswith():
response =
message == :
response =
:
response =
.socket.sendto(response.encode(), addr)
():
.lock:
clients = (.clients.keys())
addr clients:
:
.socket.sendto(message.encode(), addr)
Exception e:
()
():
.running =
.socket:
.socket.close()
()
:
():
.server_host = server_host
.server_port = server_port
.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
.socket.settimeout()
() -> :
.socket.sendto(message.encode(), (.server_host, .server_port))
data, _ = .socket.recvfrom()
data.decode()
() -> :
start = time.time()
response = .send()
latency = (time.time() - start) *
response.startswith():
server_time = (response.split()[])
latency
-
():
.socket.close()
__name__ == :
server = UDPServer()
server.start()
const net = require('net');
class TCPConnectionPool {
constructor(options = {}) {
this.host = options.host || 'localhost';
this.port = options.port || 8080;
this.minSize = options.minSize || 5;
this.maxSize = options.maxSize || 20;
this.connectionTimeout = options.connectionTimeout || 5000;
this.idleTimeout = options.idleTimeout || 30000;
this.pool = [];
this.waiting = [];
this.activeCount = 0;
this.creating = false;
}
async acquire() {
const connection = this.findAvailableConnection();
if (connection) {
return connection;
}
if (. >= .) {
.();
}
.();
}
() {
(.. > ) {
connection = ..();
(.(connection)) {
connection;
}
.(connection);
}
;
}
() {
. = ;
.++;
( {
connection = net.({
: .,
: .,
: .
});
connection.(, {
. = ;
connection. = ;
connection. = .();
(connection);
});
connection.(, {
. = ;
.--;
.();
(err);
});
connection.(, {
connection.();
.--;
});
});
}
() {
( {
..({ resolve, reject });
});
}
() {
(.. > && . < .) {
{ resolve } = ..();
.().(resolve).( {
});
}
}
() {
(!connection || connection.) {
;
}
connection. = ;
connection. = .();
(.. < .) {
..(connection);
.();
} {
.(connection);
}
}
() {
.--;
connection.();
connection.();
}
() {
(connection. || connection.) {
;
}
idleTime = .() - connection.;
idleTime < . && connection.;
}
() {
. = ..( {
(!.(connection)) {
.(connection);
;
}
;
});
}
() {
..( .(connection));
. = [];
..( ( ()));
. = [];
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/if_ether.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUFFER_SIZE 65536
typedef struct {
uint32_t src_ip;
uint32_t dst_ip;
uint16_t src_port;
uint16_t dst_port;
uint8_t protocol;
uint32_t packet_count;
uint64_t byte_count;
} FlowStats;
typedef struct {
FlowStats flows[1000];
int flow_count;
} NetworkAnalyzer;
void print_ip_header(struct ip *ip_header) {
char src_ip[INET_ADDRSTRLEN];
char dst_ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &ip_header->ip_src, src_ip, INET_ADDRSTRLEN);
inet_ntop(AF_INET, &ip_header->ip_dst, dst_ip, INET_ADDRSTRLEN);
();
(, ip_header->ip_v);
(, ip_header->ip_hl * );
(, ip_header->ip_tos);
(, ntohs(ip_header->ip_len));
(, ip_header->ip_ttl);
(, ip_header->ip_p);
(, src_ip);
(, dst_ip);
}
{
();
(, ntohs(tcp_header->th_sport));
(, ntohs(tcp_header->th_dport));
(, ntohl(tcp_header->th_seq));
(, ntohl(tcp_header->th_ack));
(, tcp_header->th_flags);
(tcp_header->th_flags & TH_SYN) ();
(tcp_header->th_flags & TH_ACK) ();
(tcp_header->th_flags & TH_FIN) ();
(tcp_header->th_flags & TH_RST) ();
(tcp_header->th_flags & TH_PUSH) ();
(tcp_header->th_flags & TH_URG) ();
();
}
{
();
(, ntohs(udp_header->uh_sport));
(, ntohs(udp_header->uh_dport));
(, ntohs(udp_header->uh_len));
}
{
( ether_header *)buffer;
( ip *)(buffer + ( ether_header));
(ntohs(eth_header->ether_type) != ETHERTYPE_IP) {
;
}
print_ip_header(ip_header);
(ip_header->ip_p == IPPROTO_TCP) {
( tcphdr *)(buffer +
( ether_header) + ( ip));
print_tcp_header(tcp_header);
} (ip_header->ip_p == IPPROTO_UDP) {
udphdr *udp_header = ( udphdr *)(buffer +
( ether_header) + ( ip));
print_udp_header(udp_header);
}
(, size - ( ether_header) - ip_header->ip_hl * );
}
{
raw_socket = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
(raw_socket < ) {
perror();
;
}
(&ifr, , (ifr));
(ifr.ifr_name, interface, IFNAMSIZ - );
(setsockopt(raw_socket, SOL_SOCKET, SO_BINDTODEVICE, &ifr, (ifr)) < ) {
perror();
close(raw_socket);
;
}
raw_socket;
}
{
raw_socket = create_raw_socket(interface);
(raw_socket < ) {
(, );
;
}
*buffer = ( *)(BUFFER_SIZE);
NetworkAnalyzer analyzer = {};
(, interface);
();
count = ;
(count < packet_count || packet_count == ) {
size = recvfrom(raw_socket, buffer, BUFFER_SIZE, , , );
(size < ) {
perror();
;
}
analyze_packet(buffer, size, &analyzer);
count++;
}
(buffer);
close(raw_socket);
}
use std::io::{self, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream, ToSocketAddrs, UdpSocket};
use std::sync::Arc;
use std::thread;
struct DualStackServer {
ipv4_addr: String,
ipv6_addr: String,
port: u16,
}
impl DualStackServer {
fn new(ipv4_addr: String, ipv6_addr: String, port: u16) -> Self {
Self { ipv4_addr, ipv6_addr, port }
}
fn start(&self) -> io::Result<()> {
let ipv4_addr = format!("{}:{}", self.ipv4_addr, self.port);
let ipv6_addr = format!("[{}]:{}", self.ipv6_addr, self.port);
let ipv4_listener = TcpListener::bind(&ipv4_addr)?;
let ipv6_listener = TcpListener::bind(&ipv6_addr)?;
println!("Server listening on IPv4: {}", ipv4_addr);
println!("Server listening on IPv6: {}", ipv6_addr);
let = Arc::(std::sync::atomic::AtomicBool::());
= running.();
thread::( || {
ipv4_listener.() {
!running_clone.(std::sync::atomic::Ordering::Relaxed) {
;
}
(stream) = stream {
.(stream);
}
}
});
ipv6_listener.() {
!running.(std::sync::atomic::Ordering::Relaxed) {
;
}
(stream) = stream {
.(stream);
}
}
(())
}
(&, stream: TcpStream) {
= stream.().();
= [; ];
(, addr);
{
= stream.(& buffer) {
() => ,
(n) => n,
(e) => {
(, addr, e);
;
}
};
(, bytes_read, addr);
= (, ::(&buffer[..bytes_read]));
(e) = stream.(response.()) {
(, addr, e);
;
}
}
(, addr);
}
}
{
socket: UdpSocket,
}
{
(addr: &) io::<> {
= UdpSocket::(addr)?;
socket.()?;
( { socket })
}
(&, message: &, broadcast_addr: &) io::<> {
.socket.(message.(), broadcast_addr)
}
(&, buffer: & []) io::<(, SocketAddr)> {
.socket.(buffer)
}
}
() io::<()> {
= DualStackServer::(
.(),
.(),
);
server.()
}