dani
dani

Reputation: 341

Send HEX values through UDP Socket

I'm trying to send an array of hexadecimal values through an udp socket but I can't only receive the firt byte 0x22. What's the problem?? Thank you in advance!!!

PD: How can I print the array with hex values?

/* UDP client in the internet domain */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <time.h>

void error(const char *);
int main()
{
   int sock, n;
   unsigned int length;
   struct sockaddr_in server;
   struct hostent *hp;
   char buffer[13]={0x22,0x00,0x0d,0xf4,0x35,0x31,0x02,0x71,0xa7,0x31,0x88,0x80,0x00};


   hp = gethostbyname("127.0.0.1");
   if (hp==0) error("Unknown host");

   sock= socket(AF_INET, SOCK_DGRAM, 0);
   if (sock < 0) error("socket");

   server.sin_family = AF_INET;
   bcopy((char *)hp->h_addr, 
        (char *)&server.sin_addr,
         hp->h_length);
   server.sin_port = htons(atoi("6666"));
   length=sizeof(struct sockaddr_in);
   while (1) {
     n=sendto(sock,buffer,strlen(buffer),0,(const struct sockaddr *)&server,length);
     if (n < 0) error("Sendto");
     printf("Sending Packet...\n");
     sleep(1);
   }
   close(sock);
   return 0;
}

void error(const char *msg)
{
    perror(msg);
    exit(0);
}

Upvotes: 0

Views: 7695

Answers (5)

Ali Anwar
Ali Anwar

Reputation: 21

Replace your code with this:

n = sendto(sock, buffer.c_str(), buffer.size() + 1, 0, (sockaddr*)&server, sizeof(server));

Upvotes: -1

mathematician1975
mathematician1975

Reputation: 21351

You are using this

  strlen(buffer)

in

  n=sendto(sock,buffer,strlen(buffer),0,(const struct sockaddr *)&server,length);

which will return 1 since the second element in buffer is 0x00

Upvotes: 1

abhi-rao
abhi-rao

Reputation: 2785

That is because you are using strlen(buffer) and buffer[1] is Null

Instead of strlen(buffer) use sizeof(buffer)

Upvotes: 2

TJD
TJD

Reputation: 11896

You don't want to use strlen(buffer), because your data isn't a string. strlen will return the length of bytes until reaching first zero.

Upvotes: 1

Mat
Mat

Reputation: 206679

.... strlen(buffer) ...

This is (part of at least) your problem. strlen is for C strings. C strings are terminated by 0x00. Your buffer has a zero as its second char, so strlen will be 1. You're sending a single byte.

Don't use strlen on binary data, use the actual number of bytes you want to send.

(And don't use string functions on the receiving side either.)

Upvotes: 1

Related Questions