我想通过一个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);
}
括号只需要'的sizeof(类型名称)',你可以在这里忽略它们:'的sizeof buffer' – wildplasser 2012-07-28 16:27:19
@wildplasser:你不必键入一个字符少收获了什么与众不同? – 2012-07-31 13:25:47
1)它使意图清晰。 2)它避免了类似'typedef struct {...} Item;项目*项目; item = malloc(sizeof(* Item));'(我上周在这里实际看到过;没有括号就是一个语法错误) – wildplasser 2012-07-31 13:51:52