【问题标题】:Socket programming issue ipv6+udpsocket编程问题ipv6+udp
【发布时间】:2019-07-04 14:30:05
【问题描述】:

我写了一个代码来生成 ipv6+UDP 数据包,我面临 sendto() 正在抛出“sendto failed : Invalid argument”,但是几乎没有修改,相同的代码适用于 ipv4+udp .有人可以帮我找出我丢失的问题吗?

    //create a socket
//int s = socket (AF_INET6, SOCK_RAW, IPPROTO_RAW);
int s = socket (AF_INET6, SOCK_RAW, IPPROTO_UDP);
if(s == -1)
{
    perror("System Error: Failed to create raw socket");
    exit(1);
}
    int one=0;
const int *val = &one;

if(setsockopt(s, 41, IP_HDRINCL, val, sizeof(one)) < 0)
{
    perror("setsockopt() error");
    exit(-1);
}

iph  = (struct ip6_hdr*) datagram;
udph = (struct udphdr *) (datagram + sizeof (struct ip6_hdr));
uint32_t tot_pkts = config->num_pkts ;
while(tot_pkts)
{
    //if(send(s, (void*) iph, ntohs(iph->ip6_plen), 0 ) < 0)
    //if (sendto (s, (char*) udph, ntohs(iph->ip6_plen),  0, (struct sockaddr *) (&sin6), sizeof (sin6)) < 0)
    if (sendto (s, (char*) datagram, (ntohs(iph->ip6_plen) + sizeof(struct ip6_hdr)),  0, (struct sockaddr *) (&sin6), sizeof (sin6)) < 0){
        printf("Length ip:%d \n",ntohs(iph->ip6_plen));
        perror("sendto failed ");
    }
    else
    {
        printf("Sending ...Length ip:%d udp:%d\n", ntohs(iph->ip6_plen),ntohs(udph->len));
    }
    tot_pkts--;
}

【问题讨论】:

  • 你能ping通你要连接的主机吗?
  • 可以ping通。

标签: linux c sockets


【解决方案1】:
 if(setsockopt(s, 41, IP_HDRINCL, val, sizeof(one)) < 0)

IP_HDRINCL 不适用于 IPv6,而只能用于 IPv4。在 Linux 上,您可以使用 IPV6_HDRINCL(在 setsockopt 中与 IPPROTO_IPV6 结合使用)。

【讨论】:

  • 您好,感谢您的更新。不幸的是,我仍然面临同样的问题。即使我评论 put setsockopt() 并尝试过,仍然存在问题。
  • @SakthivelThandabani:请参阅stackoverflow.com/a/47779888/3081018,特别是它所链接的内容。来自nick-black.com/dankwiki/index.php/Packet_sockets"当使用 IPv6 原始套接字时,sin6_port 必须设置为 0 以避免出现 EINVAL("无效参数")错误。"。如果它仍然不起作用,请提供一个完整但最小的示例,而不是只显示您认为相关的部分。
  • remote.sin6_port = 0; 这有帮助。谢谢史蒂芬
猜你喜欢
  • 2011-02-01
  • 2012-03-22
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
  • 2012-02-11
相关资源
最近更新 更多