Problem with socket code C++ when send and hex message

Viewed 326

I try to send hex data to another device. The compilation does not lead to errors. But when I launch the function from the terminal nothing happens but a light should turn on. I put a cout on connect () to see if I have some connection problems but it answers 0 (so I have no problems) maybe it's how I write the hex code? Besides the code I also insert the command line that I execute with the Hex code. The strange thing is that if I use any program like PacketSender with the same parameters it works.

./main 192.168.2.170 26810000A7

in attachment I also add the screenshot made on PacketSender.In addition what I can say is that if I leave the recv () command in the code once I give the command from the terminal the prompt remains pending ... if instead I comment the recv () once I give the command from the prompt it returns to the prompt but without doing anything (so without turning on the light). Does anyone have any ideas?

enter image description here

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

using namespace std;

// per compilare gcc connect_PE.cpp -lstdc++ -o main
int main(int argc, char *argv[])
{
    int sockfd, n;
    struct sockaddr_in servaddr;

    std::string serveraddr = argv[1];

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

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

    connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    cout << connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    const std::string hex = argv[2];

    char *number = strcpy(new char[hex.length() + 1], hex.c_str());


    send(sockfd, &number, 8, 0);
    recv(sockfd, &number, 8, 0);

}
2 Answers

You’re passing the address of number when you should be passing its value.

Or even better, just pass hex.data() or &hex[0] – there’s no point in copying it.

Also note that you are sending a string of characters, not numbers in hexadecimal form.
(The first char is not 0x26 - that is, 38 - but ’2’, wich is probably 50.)

If you want to send the corresponding numbers, you need to convert the input first.

Sockets work very poorly with everything that is not char*, so it is better to immediately send a string from the terminal argument, and perform all the necessary transformations on the server.

Related