简体   繁体   中英

Sending hex over a TCP Socket in C/C++

I am having difficulty using TCP Sockets to send hex values. Specifically I want to send a hex value (such as 0x123456) across a socket so that the TCP data send, not the ASCII representation, is the value I desire. I am currently only able to send the value I want as a ASCII string, any help to send the hex value across the socket is appreciated.

Below is the code I have written:

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <unistd.h>

using namespace std;

int main(int argc, char**argv) {
    int sockfd, n;
    struct sockaddr_in servaddr;
    char sendline[1000];
    char recvline[1000];

    std::string serveraddr = "127.0.0.1";

    sockfd = socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr(serveraddr.c_str());
    servaddr.sin_port = htons(1234);

    connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

    int number = 0x123456;

    int sendsize;
    sendsize = snprintf(sendline, sizeof(sendline), "%x", number);

    send(sockfd, sendline, sendsize * sizeof(char), 0);

}

You can send() any data you want, it does not have to be a character string. Sockets operate on raw bytes, not text. So you can send your number directly:

int number = 0x123456;
send(sockfd, (char*)&number, sizeof(number), 0);

Same with reading:

int number = 0;
recv(sockfd, (char*)&number, sizeof(number), 0);

With that said, it is customary (but not required) that multi-byte numbers be transmitted in network byte order:

int number = htonl(0x123456);
send(sockfd, (char*)&number, sizeof(number), 0);

int number = 0;
recv(sockfd, (char*)&number, sizeof(number), 0);
number = ntohl(number);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM