linux下raw socket发广播包失败。
代码如下,代码理论上是没问题的,问题就是当我在虚拟机的CentOS下,root用户下执行这个程序,通过NAT的方式连接网络,执行到sendto后,函数的返回值一直都是-1,不知道是什么原因。我只是创建了一个ICMP请求地址掩码的包,然后就发送,我认为可能是环境的问题。所以想问一下在虚拟机下这样做有什么应该要注意的吗?(我相信不是代码问题,没有写注释,可以不用麻烦去看代码)
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip_icmp.h>
#include <string.h>
#include <error.h>
static unsigned short checksum(int numwords, unsigned short *buff);
int main(int argc, char *argv[])
{
unsigned char buffer[1024];
int sockfd = 0;
int len = 0;
struct icmphdr *icmph;
struct sockaddr_in addr;
memset((void *)buffer, 0, 1024);
if (sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP) < 0)
{
fprintf(stdout, "Socket Create Error\n");
return 0;
}
icmph = (struct icmphdr *)buffer;
icmph->type = ICMP_ADDRESS; // 0x17
icmph->code = 0x00;
(icmph->un).echo.id = 0x5555;
(icmph->un).echo.sequence = 0xaaaa;
icmph->checksum = 0x00;
inet_aton(argv[1], &addr.sin_addr);
len = 12;
// ready to send
icmph->checksum = checksum(len / 2, (unsigned short *)icmph);
len = sendto(sockfd, buffer, len, 0,
(struct sockaddr *)&addr, sizeof(addr));
if (len < 0)
{
fprintf(stdout, "Send Error %d\n", len);
fprintf(stdout, "%s\n", len);
close(sockfd);
return 0;
}
else
fprintf(stdout, "Send Okay\n");
while (1)
{
}
return 0;
}
static unsigned short checksum(int numwords, unsigned short *buff)
{
unsigned long sum;
for (sum = 0; numwords > 0; numwords--)
sum += *buff++;
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
return ~sum;
}
伊达兔兔子
10 years, 9 months ago