c - 发送 UDP 数据包并从 C 中的路由器接收 ICMP 响应

标签 c sockets udp raw-sockets icmp

我正在尝试编写一个 C 程序,该程序将 UDP 数据包发送到给定的 IP 地址,并等待路由器的 ICMP 响应,告知生存时间已过期。它保持非常简单,因为我只想首先了解该机制。我需要的是有人检查我的代码,就错误和缺失提供反馈。我在 C 编程方面非常缺乏经验,但我必须将其作为一项任务来完成 - 尽我所能理解它......

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/ip.h> 

// The packet length
#define PCKT_LEN 8192 

// Source IP, source port, target IP, target port from the command line arguments
int main(int argc, char *argv[])
{
    int send, recv, resp;
    int ttl = 1; // Time to live
    char buffer[PCKT_LEN];

    // Destination address
    struct sockaddr_in dst;

    // ICMP Response
    struct msghdr icmp;

    memset(buffer, 0, PCKT_LEN);

    // Create a raw socket with UDP protocol
    if ((send = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
    {
        printf("Could not process socket() [send].\n");
        return EXIT_FAILURE;
    }

    // ICMP Socket
    if ((recv = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
    {
        printf("Could not process socket() [recv].\n");
        return EXIT_FAILURE;
    }

    dst.sin_family      = AF_INET;
    dst.sin_addr.s_addr = inet_addr("74.125.39.106");
    dst.sin_port        = htons(60001);

    // Define time to life
    if(setsockopt(send, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl)) < 0)
    {
        printf("Could not process setsockopt().\n");
        return EXIT_FAILURE;
    }

    if(sendto(send, buffer, sizeof(buffer), 0, (struct sockaddr *) &dst, sizeof(dst)) < 0)
    {
        printf("Could not process sendto().\n");
        return EXIT_FAILURE;
    }


    if((resp = recvmsg(recv, (struct msghdr *) &icmp, IP_RECVERR|MSG_ERRQUEUE)) < 0 )
    {
        printf("Could not process recvmsg().\n");
        return EXIT_FAILURE;
    }

    close(send);
    close(recv);

    return 0;
}

我一直收到“无法处理 recvmsg()”。我不知道还能尝试什么。我想收到 ICMP 应答并读取其发件人 IP 地址。

期待有用的提示。

最好的问候!

最佳答案

我一般用

recvfrom(serversock, buf, 100, 0, (struct sockaddr *)&rcv,&size);

printf("Received packet from %s:%d\nData: %s\n\n", inet_ntoa(rcv.sin_addr), ntohs(rcv.sin_port), buf);

关于c - 发送 UDP 数据包并从 C 中的路由器接收 ICMP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4888285/

相关文章:

c - 如何计算套接字中的时间

c - 如何通过UDP发送结构并在另一端接收?

c - 如何获得数字的第一个设置位的位置

c - 避免使用宏将声明与实现分开

java - 广播服务器发现

c++ - 如何在 QNX 中将 UDP 套接字设置为非阻塞

udp - 如果我的 udp 包大于 mtu 会发生什么

GCC 可以不提示 undefined reference 吗?

c - 在 C 中的单独函数中为数组赋值

arrays - float 组到字节数组,反之亦然