0

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);
}
4

5 に答える 5

2

これは、strlen(buffer)を使用していて、buffer[1]がNullであるためです。

strlen(buffer) 使用する代わりにsizeof(buffer)

于 2012-07-28T16:24:13.943 に答える
1
.... strlen(buffer) ...

これは(少なくとも一部は)あなたの問題です。strlenCストリング用です。C文字列は。で終了し0x00ます。バッファの2番目の文字はゼロなので、strlen1になります。1バイトを送信しています。

バイナリデータには使用せずstrlen、送信する実際のバイト数を使用してください。

(また、受信側でも文字列関数を使用しないでください。)

于 2012-07-28T16:23:53.863 に答える
1

strlen(buffer)データは文字列ではないため、を使用する必要はありません。strlenは、最初のゼロに達するまでのバイト長を返します。

于 2012-07-28T16:24:04.440 に答える
1

これを使用しています

  strlen(buffer)

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

バッファの2番目の要素が0x00であるため、これは1を返します。

于 2012-07-28T16:24:46.650 に答える
-1

Replace your code with this:

n = sendto(sock, buffer.c_str(), buffer.size() + 1, 0, (sockaddr*)&server, sizeof(server));
于 2021-02-01T13:54:45.080 に答える