roger 发表于 2020-6-15 20:54:57

C/C++ 通过Socket 传输结构体

  本质上socket无法传输结构体,我们只有将结构体装换为字节数组,或者是字符串格式来传输,到了服务端在强制类型转换一下即可,下面的代码,直接改改,可用于收集目标主机数据。
  客户端:
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")

typedef struct Info
{
char client_name;
char buffer;
}message;

message msg;


void GetSysInfo()
{
SYSTEM_INFO sysInfo;
}

int main()
{
WSADATA WSAData;
SOCKET sock;

WSAStartup(MAKEWORD(2, 0), &WSAData);
sock = socket(AF_INET, SOCK_STREAM, 0);

struct sockaddr_in ClientAddr;
ClientAddr.sin_family = AF_INET;
ClientAddr.sin_port = htons(15001);
ClientAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

connect(sock, (LPSOCKADDR)&ClientAddr, sizeof(ClientAddr));

// 首先需要定义一个变量
char snd_buf = { 0 };

// 将数据拷贝到结构中
strcpy(msg.client_name, "lyshark");
strcpy(msg.buffer, "bbbbbb");

// 发送字节序
memcpy(snd_buf, &msg, sizeof(message));
send(sock, snd_buf, sizeof(snd_buf), 0);

closesocket(sock);
WSACleanup();
return 0;
}
  服务端;
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#define PORT 15001
#define ERROR 0
#define BUFFER_SIZE 1024


typedef struct Info
{
char client_name;
char buffer;
}message;

int main()
{
WSADATA WSAData;

WSAStartup(MAKEWORD(2, 0), &WSAData);

SOCKET sock;
sock = socket(AF_INET, SOCK_STREAM, 0);

struct sockaddr_in ServerAddr;   
ServerAddr.sin_family = AF_INET;         
ServerAddr.sin_port = htons(PORT);      
ServerAddr.sin_addr.s_addr = INADDR_ANY;

bind(sock, (LPSOCKADDR)&ServerAddr, sizeof(ServerAddr));
listen(sock, 10);

SOCKET msgsock;      
// 用于接收结构
char buf = { 0 };

msgsock = accept(sock, (LPSOCKADDR)0, (int *)0);

recv(msgsock, buf, sizeof(buf), 0);
// 接收到结构,强制类型转换
message *msg = (message*)buf;

printf("%s \n", msg->client_name);
printf("%s \n", msg->buffer);

closesocket(sock);
WSACleanup();

system("pause");
return 0;
}


页: [1]
查看完整版本: C/C++ 通过Socket 传输结构体