你这个问题比较宽泛,我分几种常见场景给你讲,在 Linux + C++ 下“配置/使用网络”通常怎么做。
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main() {
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = INADDR_ANY;
bind(server_fd, (sockaddr*)&addr, sizeof(addr));
listen(server_fd, 5);
std::cout << "Listening...\n";
int client_fd = accept(server_fd, nullptr, nullptr);
char buf[1024] = {0};
read(client_fd, buf, sizeof(buf));
std::cout << "Client: " << buf << std::endl;
close(client_fd);
close(server_fd);
}
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
connect(sock, (sockaddr*)&addr, sizeof(addr));
send(sock, "hello", 5, 0);
close(sock);
}
编译:
g++ server.cpp -o server
g++ client.cpp -o client
ip addr
ip route
sudo ip addr add 192.168.1.100/24 dev eth0
sudo ip link set eth0 up
编辑:
sudo vim /etc/netplan/01-netcfg.yaml
示例:
network:
version: 2
ethernets:
eth0:
addresses: [192.168.1.100/24]
gateway4: 192.168.1.1
nameservers:
addresses: [8.8.8.8]
应用:
sudo netplan apply
如果你不想手写 socket:
| 库 | 特点 |
|---|---|
| Boost.Asio | 最主流 |
| libcurl | HTTP 请求 |
| ZeroMQ | 高性能通信 |
| muduo | 中文社区常用 |
#include <boost/asio.hpp>
using namespace boost::asio;
int main() {
io_context io;
ip::tcp::socket sock(io);
sock.connect(ip::tcp::endpoint(ip::make_address("127.0.0.1"), 8080));
}
✅ 防火墙
sudo ufw allow 8080
✅ 权限
✅ 头文件
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
比如:
我可以直接给你对应完整示例。