c++获取tcp网络发送过来的16进制的字符串
时间: 2024-01-27 20:03:33 浏览: 95
获取网络字符串
在C++中,可以使用socket编程来实现TCP网络通信,获取网络发送过来的16进制字符串可以按照以下步骤进行:
1. 创建socket对象并连接服务器:
```c++
#include <sys/socket.h>
#include <arpa/inet.h>
int sock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(1234);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
```
其中,`127.0.0.1`为服务器的IP地址,`1234`为服务器的端口号,需要根据实际情况进行替换。
2. 接收网络发送的数据:
```c++
char buffer[1024];
int recv_len = recv(sock, buffer, sizeof(buffer), 0);
```
`recv`函数用于接收网络发送过来的数据,`buffer`为接收缓存区,`sizeof(buffer)`为缓存区大小,`recv_len`为实际接收到的数据长度。
3. 将接收到的数据转换为16进制字符串:
```c++
std::string hex_str = "";
for (int i = 0; i < recv_len; i++) {
char hex[3];
sprintf(hex, "%02x", (unsigned char)buffer[i]);
hex_str += hex;
}
```
`sprintf`函数用于将每个字节转换为2位的16进制字符串,然后拼接起来形成完整的16进制字符串。
完整的代码示例:
```c++
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string>
#include <iostream>
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(1234);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
char buffer[1024];
int recv_len = recv(sock, buffer, sizeof(buffer), 0);
std::string hex_str = "";
for (int i = 0; i < recv_len; i++) {
char hex[3];
sprintf(hex, "%02x", (unsigned char)buffer[i]);
hex_str += hex;
}
std::cout << "Received hex string: " << hex_str << std::endl;
close(sock);
return 0;
}
```
阅读全文