2012-07-28 316 views
0

我想通過一個udp套接字發送一個十六進制值的數組,但我不能只接收firt字節0x22。有什麼問題??先謝謝你!!!通過UDP發送HEX值套接字

PD:如何以十六進制值打印數組?

/* 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); 
} 

回答

2

那是因爲你正在使用的strlen(緩衝)和緩衝[1]是空

代替strlen(buffer)使用sizeof(buffer)

+0

括號只需要'的sizeof(類型名稱)',你可以在這裏忽略它們:'的sizeof buffer' – wildplasser 2012-07-28 16:27:19

+0

@wildplasser:你不必鍵入一個字符少收穫了什麼與衆不同? – 2012-07-31 13:25:47

+0

1)它使意圖清晰。 2)它避免了類似'typedef struct {...} Item;項目*項目; item = malloc(sizeof(* Item));'(我上週在這裏實際看到過;沒有括號就是一個語法錯誤) – wildplasser 2012-07-31 13:51:52

1
.... strlen(buffer) ... 

這是你的問題(至少部分)。 strlen用於C字符串。 C字符串由0x00終止。您的緩衝區的第二個字符爲零,因此strlen將爲1.您正在發送一個字節。

請勿在二進制數據上使用strlen,請使用您想要發送的實際字節數。

(不要在接收端使用字符串函數無論是。)

1

你不想使用strlen(buffer),因爲你的數據不是一個字符串。 strlen將返回字節的長度,直到達到第一個零。

1

您使用此

strlen(buffer) 

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

從第二個元素開始將返回1噸緩衝區爲0x00