这里写自定义目录标题
- 线程 防止阻塞
- 1
- 2
- 3 windows下
- 4
https://zhuanlan.zhihu.com/p/139454200
https://www.bilibili.com/video/BV1eg411G7pW/?spm_id_from=333.337.search-card.all.click&vd_source=e7d12c9f66ab8294c87125a95510dac9
with socket.socket() as s:
s.bind()
s.listern()
c,addr = s.accept()
0 0 0 0 特殊的地址 单纯代表主机端任意网卡都可以使用这个socket进行通信
后面接受客户端ip地址
一次接受最大长度 1024个字节
nc 服务器ip地址 端口号 netcat
nmap
repr() 函数将对象转化为供解释器读取的形式。
返回一个对象的 string 格式。
线程 防止阻塞
https://zhuanlan.zhihu.com/p/100151937
TCP/IP是计算机网络中的一个协议族,用于在网络中实现数据通信和互联网连接。C++语言可以使用Socket库来实现TCP/IP通信。
以下是基本的TCP/IP代码示例:
导入Socket库
cpp
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
创建套接字
cpp
int sock = socket(AF_INET, SOCK_STREAM, 0);
设置服务器地址
cpp
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8080);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
连接服务器
cpp
connect(sock, (struct sockaddr*) &serverAddr, sizeof(serverAddr));
发送数据
cpp
const char* sendData = "Hello Server!";
send(sock, sendData, strlen(sendData), 0);
接收数据
cpp
char recvData[1024] = {0};
recv(sock, recvData, sizeof(recvData), 0);
printf("Received: %s\n", recvData);
关闭套接字
cpp
close(sock);
这个简单的代码示例展示了如何使用C++语言进行TCP/IP通信。当然,在实际开发中,还需要考虑更多的细节和错误处理,但这个示例可以作为一个起点。
1
以下是一个基本的Tcp/ip服务器和客户端代码(使用C++编写),其中服务器将侦听端口并接受传入连接,然后读取来自客户端的消息并返回响应。客户端将连接到服务器,并发送一条消息,然后等待响应。
服务器代码:
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(void)
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
std::cerr << "ERROR opening socket" << std::endl;
exit(1);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 12345;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
std::cerr << "ERROR on binding" << std::endl;
exit(1);
}
listen(sockfd, 5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) {
std::cerr << "ERROR on accept" << std::endl;
exit(1);
}
bzero(buffer, 256);
n = read(newsockfd, buffer, 255);
if (n < 0) {
std::cerr << "ERROR reading from socket" << std::endl;
exit(1);
}
std::cout << "Here is the message: " << buffer << std::endl;
n = write(newsockfd, "I got your message", 18);
if (n < 0) {
std::cerr << "ERROR writing to socket" << std::endl;
exit(1);
}
return 0;
}
在服务器代码中,我们首先创建一个套接字(socket()),然后绑定到指定的端口和IP地址(bind())。然后我们侦听传入连接请求(listen())并等待客户端连接(accept())。一旦连接建立,我们从套接字读取数据(read()),然后将响应写回到套接字(write())。
客户端代码:
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3) {
std::cerr << "usage " << argv[0] << " hostname port" << std::endl;
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
std::cerr << "ERROR opening socket" << std::endl;
exit(1);
}
server = gethostbyname(argv[1]);
if (server == NULL) {
std::cerr << "ERROR, no such host" << std::endl;
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
std::cerr << "ERROR connecting" << std::endl;
exit(1);
}
std::cout << "Please enter the message: ";
bzero(buffer,256);
std::cin.getline(buffer,255);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0) {
std::cerr << "ERROR writing to socket" << std::endl;
exit(1);
}
2
这两个头文件是用于在不同操作系统上进行网络编程的。具体来说:
<sys/socket.h> 和 <sys/types.h> 是用于在类UNIX系统上进行网络编程的头文件,提供了许多与套接字相关的函数和数据结构。
Winsock 是用于在Windows操作系统上进行网络编程的API。它定义了一组函数、数据结构和常量,用于创建和操作套接字。
因此,<sys/socket.h> 和 <sys/types.h> 主要用于类UNIX系统,而Winsock主要用于Windows系统。它们之间的区别在于它们所定义的函数和数据结构以及它们在不同操作系统上的实现方式。如果您想在不同的操作系统上进行网络编程,您需要使用相应的头文件和API。
3 windows下
#include <iostream>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
int main()
{
WSADATA wsaData;
SOCKET serverSocket, clientSocket;
SOCKADDR_IN serverAddr, clientAddr;
int clientAddrLen = sizeof(clientAddr);
char buf[1024] = { 0 };
int ret;
// 初始化 Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
std::cerr << "WSAStartup failed" << std::endl;
return -1;
}
// 创建套接字
serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket == INVALID_SOCKET)
{
std::cerr << "socket failed: " << WSAGetLastError() << std::endl;
WSACleanup();
return -1;
}
// 填充地址结构体
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8888);
serverAddr.sin_addr.s_addr = INADDR_ANY;
// 绑定套接字到指定地址和端口
if (bind(serverSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR)
{
std::cerr << "bind failed: " << WSAGetLastError() << std::endl;
closesocket(serverSocket);
WSACleanup();
return -1;
}
// 开始监听连接请求
if (listen(serverSocket, 5) == SOCKET_ERROR)
{
std::cerr << "listen failed: " << WSAGetLastError() << std::endl;
closesocket(serverSocket);
WSACleanup();
return -1;
}
std::cout << "waiting for connection..." << std::endl;
// 接受连接请求
clientSocket = accept(serverSocket, (SOCKADDR*)&clientAddr, &clientAddrLen);
if (clientSocket == INVALID_SOCKET)
{
std::cerr << "accept failed: " << WSAGetLastError() << std::endl;
closesocket(serverSocket);
WSACleanup();
return -1;
}
std::cout << "connection accepted" << std::endl;
// 接收客户端发送的数据
ret = recv(clientSocket, buf, sizeof(buf), 0);
if (ret > 0)
{
std::cout << "received data from client: " << buf << std::endl;
}
// 关闭套接字
closesocket(clientSocket);
closesocket(serverSocket);
WSACleanup();
return 0;
}
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
// 初始化Winsock库
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
std::cout << "Failed to initialize Winsock" << std::endl;
return 1;
}
// 创建套接字
SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket == INVALID_SOCKET) {
std::cout << "Failed to create socket: " << WSAGetLastError() << std::endl;
WSACleanup();
return 1;
}
// 绑定套接字到端口
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(8888);
if (bind(serverSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
std::cout << "Failed to bind socket: " << WSAGetLastError() << std::endl;
closesocket(serverSocket);
WSACleanup();
return 1;
}
// 监听连接请求
if (listen(serverSocket, SOMAXCONN) == SOCKET_ERROR) {
std::cout << "Failed to listen on socket: " << WSAGetLastError() << std::endl;
closesocket(serverSocket);
WSACleanup();
return 1;
}
std::cout << "Server is listening on port 8888..." << std::endl;
// 接受客户端连接
sockaddr_in clientAddr;
int clientAddrSize = sizeof(clientAddr);
SOCKET clientSocket = accept(serverSocket, (sockaddr*)&clientAddr, &clientAddrSize);
if (clientSocket == INVALID_SOCKET) {
std::cout << "Failed to accept client connection: " << WSAGetLastError() << std::endl;
closesocket(serverSocket);
WSACleanup();
return 1;
}
std::cout << "Client connected from " << inet_ntoa(clientAddr.sin_addr) << ":" << ntohs(clientAddr.sin_port) << std::endl;
// 发送和接收数据
char buffer[1024];
int recvSize, sendSize;
do {
recvSize = recv(clientSocket, buffer, sizeof(buffer), 0);
if (recvSize > 0) {
std::cout << "Received " << recvSize << " bytes of data: " << buffer << std::endl;
sendSize = send(clientSocket, buffer, recvSize, 0);
if (sendSize == SOCKET_ERROR) {
std::cout << "Failed to send data to client: " << WSAGetLastError() << std::endl;
break;
}
} else if (recvSize == 0) {
std::cout << "Client disconnected" << std::endl;
} else {
std::cout << "Failed to receive data from client: " << WSAGetLastError() << std::endl;
break;
}
} while (true);
// 关闭套接字和Winsock库
closesocket(clientSocket);
closesocket(serverSocket);
WSACleanup();
return 0;
}
上述代码实现了一个简单的TCP/IP服务器,该服务器监听端口号8888,等待客户端连接并接收数据。对于每个成功接收到的数据包,服务器将其原封不动地发送回给客户端。
客户端
#include <iostream>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
int main()
{
WSADATA wsaData;
SOCKET clientSocket;
SOCKADDR_IN serverAddr;
char buf[1024] = "Hello, server!";
int ret;
// 初始化 Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
std::cerr << "WSAStartup failed" << std::endl;
return -1;
}
// 创建套接字
clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET)
{
std::cerr << "socket failed: " << WSAGetLastError() << std::endl;
WSACleanup();
return -1;
}
// 填充地址结构体
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8888);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
// 连接到服务端
if (connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR)
{
std::cerr << "connect failed: " << WSAGetLastError() << std::endl;
closesocket(clientSocket);
WSACleanup();
return -1;
}
std::cout << "connected to server" << std::endl;
// 发送数据到服务端
ret = send(clientSocket, buf, strlen(buf), 0);
if (ret == SOCKET_ERROR)
4
该语句是一个编译指令,用于在Windows平台上的C/C++程序中链接Winsock库(ws2_32.lib)。当编译器编译源代码时,它将自动地把所需的库文件链接到可执行文件中。通过在源代码中使用#pragma comment(lib,“ws2_32.lib”)语句,我们可以避免手动指定库文件名称和路径,从而简化编译过程并确保程序能够正确运行。
具体来说,这个指令告诉编译器在链接阶段将ws2_32.lib库文件包含在生成的程序中,以便程序能够使用其中定义的Winsock API函数。Winsock库提供了一组用于网络编程的API函数,例如创建套接字、发送和接收数据等。
以下是一个基本的TCP/IP客户端代码,使用C++编写,可以在Windows系统上运行:
#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#pragma comment(lib, "Ws2_32.lib")
using namespace std;
int main() {
// 初始化Winsock
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
cerr << "WSAStartup failed: " << result << endl;
return 1;
}
// 创建套接字
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
cerr << "socket creation failed: " << WSAGetLastError() << endl;
WSACleanup();
return 1;
}
// 设置服务器地址和端口
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(12345); // 这里假设服务器端口为 12345
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 这里假设服务器IP为本地
// 连接服务器
result = connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr));
if (result != 0) {
cerr << "connect failed: " << WSAGetLastError() << endl;
closesocket(clientSocket);
WSACleanup();
return 1;
}
// 发送消息
const char* message = "Hello, server!";
result = send(clientSocket, message, strlen(message), 0);
if (result == SOCKET_ERROR) {
cerr << "send failed: " << WSAGetLastError() << endl;
closesocket(clientSocket);
WSACleanup();
return 1;
}
// 接收服务器回复
char buffer[1024];
result = recv(clientSocket, buffer, 1024, 0);
if (result == SOCKET_ERROR) {
cerr << "recv failed: " << WSAGetLastError() << endl;
closesocket(clientSocket);
WSACleanup();
return 1;
}
buffer[result] = '\0';
cout << "Server response: " << buffer << endl;
// 关闭套接字
closesocket(clientSocket);
// 清理Winsock
WSACleanup();
return 0;
}
这个程序执行以下步骤:
- 初始化Winsock:使用WSAStartup函数初始化Winsock库。Winsock库是Windows下用来实现网络通信的API。
- 创建套接字:使用socket函数创建一个套接字,该套接字用于与服务器建立连接。
- 设置服务器地址和端口:创建一个 sockaddr_in 结构体,用于存储服务器的IP地址和端口号。
- 连接服务器:使用connect函数连接到服务器。
- 发送消息:使用send函数向服务器发送一条消息。
- 接收服务器回复:使用recv函数接收服务器发送的回复消息。
- 关闭套接字:使用closesocket函数关闭套接字。
- 清理Winsock:使用WSACleanup函数释放Winsock库。
需要注意的是,一旦连接成功,就可以使用send和recv函数在客户端和服务器之间交换数据。在这个例子中,我们只发送了一条简单的消息,并接收了服务器的回复。实际应用中,需要根据具体需求进行修改。另外,在使用完套接字后,记得关闭它,以释放资源。
此外,客户端程序还需要链接Winsock库,这可以通过#pragma comment指令来完成,如上面代码所示。