gpt4 book ai didi

c - 原始套接字 : Receiver printing garbage values

转载 作者:太空宇宙 更新时间:2023-11-04 06:39:23 25 4
gpt4 key购买 nike

我正在尝试使用发送器和使用原始套接字的接收器程序发送字符数组。我能够获得在接收方发送的正确字节数,但打印出的值是垃圾。有人可以帮我吗?

传送器:

int create_raw_socket(char *dev) 
{
struct sockaddr_ll sll;
struct ifreq ifr;
int fd, ifi, rb;

bzero(&sll, sizeof(sll));
bzero(&ifr, sizeof(ifr));

fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));

assert(fd != -1);

strncpy((char *)ifr.ifr_name, dev, IFNAMSIZ);
ifi = ioctl(fd, SIOCGIFINDEX, &ifr);
assert(ifi != -1);
sll.sll_protocol = htons(ETH_P_ALL);
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
rb = bind(fd, (struct sockaddr *)&sll,sizeof(sll));
assert(rb != -1);

return fd;
}


int SendPacket(char *dev ,unsigned char *send_packet, int packet_len)
{
int num_sent= 0;
int sockaddress = create_raw_socket(dev);

if((num_sent = write(sockaddress, &send_packet, packet_len)) != packet_len)
{

close(sockaddress);
return 0;
}
else
{
close(sockaddress);
return 1;
}

}


int main(int argc, char**argv)
{
int x,fd,s;

char *send_packet="HELLO";

int len = sizeof(send_packet);

while(1)
{

if(!SendPacket((argv[1]), send_packet, len))
perror("Error sending packet");
else
printf("Packet sent successfully with payload : %s\n" ,send_packet);
}
return 0;
}

接收者:

int main(int argc, char **argv)
{
struct sockaddr addr;
int sock_fd, fromlen,s;
char buf[PACKET_LENGTH];
char *dev = argv[1];


while(1)
{

fromlen=sizeof(addr);
sock_fd = create_raw_socket(dev); /* Creating the raw socket */
int x= recvfrom(sock_fd,&buf,sizeof(buf),0,&addr,&fromlen);
printf("\n Number of bytes of data received is %d \n",x);

printf("\nPayload Received from client... is %s \n", buf);

close(sock_fd);

}
return 0;
}

最佳答案

改变

write(sockaddress, &send_packet, packet_len)

write(sockaddress, send_packet, packet_len)

send_packet 已经是要发送的buffer的地址,如果你取这个地址的地址(更准确的说是持有地址的变量的地址),你会读错内存缓冲区

recvfrom 类似:

recvfrom(sock_fd, buf, sizeof(buf), 0, &addr, &fromlen)

关于c - 原始套接字 : Receiver printing garbage values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10704657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com