13,840
社区成员
发帖
与我相关
我的任务
分享
怎么用纯C写一个可以收发16进制的tcp客户端程序啊????
自己写的程序只能发送字符,不会转成16进制进行发送,应该怎么办。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define BUF_SIZE 1024
int main(int argc, char* argv[])
{
if (argc < 3) {
printf("Usage: %s <server_ip> <server_port>\n", argv[0]);
return 1;
}
const char* server_ip = argv[1];
const int server_port = atoi(argv[2]);
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("WSAStartup failed\n");
return 1;
}
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET) {
printf("socket failed\n");
WSACleanup();
return 1;
}
SOCKADDR_IN servAddr;
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr(server_ip);
servAddr.sin_port = htons(server_port);
if (connect(sock, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR) {
printf("connect failed\n");
closesocket(sock);
WSACleanup();
return 1;
}
printf("Connected to server: %s:%d\n", server_ip, server_port);
char send_buf[BUF_SIZE], recv_buf[BUF_SIZE];
while (1) {
printf("Enter 16-bit hex data to send (e.g. 0x1234): ");
if (!fgets(send_buf, BUF_SIZE, stdin)) {
printf("fgets failed\n");
break;
}
// Convert hex string to integer
int data = strtol(send_buf, NULL, 16);
// Send data to server
int len = send(sock, (char*)&data, sizeof(data), 0);
if (len <= 0) {
printf("send failed\n");
break;
}
// Receive response from server
len = recv(sock, recv_buf, BUF_SIZE, 0);
if (len <= 0) {
printf("recv failed\n");
break;
}
// Print response in hex format
printf("Received response: 0x");
for (int i = 0; i < len; i++) {
printf("%02x", recv_buf[i] & 0xff);
}
printf("\n");
}
closesocket(sock);
WSACleanup();
return 0;
}