如何启用 ss(另一个用于调查套接字的实用程序)来查看 Linux 主机上加入的多播组 IP 地址?

问题描述 投票:0回答:1

我可以使用一个内部工具,该工具可用于加入多播 IP:PORT 并将数据包捕获为 pcap 文件,但该工具没有实现。

当我运行该工具时,

netstat
ss
都可以用来查看加入的组播IP地址。

例如:

$ netstat -gn|grep 224.0.115.66
sfc2            1      224.0.115.66

$ ss -uan|grep 224.0.115.66
UNCONN 0      0       224.0.115.66:6000      0.0.0.0:*

我编写了一个简单的c代码,可用于加入多播组。我遇到的问题是,当我运行我的应用程序时,只有 netstat 可以找到加入的多播组,但 ss 除外。

$ netstat -gn|grep 224.0.115.66
sfc2            1      224.0.115.66

$ ss -uan|grep 224.0.115.66

问题>我认为必须进行一些额外的配置才能使

ss
看到加入的多播组IP地址。有人可以告诉我是否需要在代码中加入任何特殊处理,以便
ss
可以检测到加入的多播组 IP:PORT 类似于
netstat
可以做的事情?

谢谢你

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    struct sockaddr_in multicast_addr;
    struct ip_mreq mreq;
    int sockfd;

    // Create a UDP socket
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket");
        exit(1);
    }

    // Set up the multicast address structure
    memset(&multicast_addr, 0, sizeof(multicast_addr));
    multicast_addr.sin_family = AF_INET;
    multicast_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    multicast_addr.sin_port = htons(6000);

    // Bind the socket to the multicast address
    if (bind(sockfd, (struct sockaddr *)&multicast_addr, sizeof(multicast_addr)) < 0) {
        perror("bind");
        exit(1);
    }

    // Join the multicast group
    memset(&mreq, 0, sizeof(mreq));
    mreq.imr_multiaddr.s_addr = inet_addr("224.0.115.66");
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
    if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
        perror("setsockopt");
        exit(1);
    }

    printf("Joined multicast group successfully\n");

    // You can now receive data from the multicast group using this socket
    // do sth thing here so that the application doesn't immediately exit!!!
    
    // Close the socket when done
    close(sockfd);

    return 0;
}
c udp netstat multicastsocket ss
1个回答
0
投票

问题是

netstat -ng
ss -uan
不做同样的事情。

运行

netstat -ng
将为您提供加入的多播组的列表。相反,
ss -uan
为您提供所有打开的 UDP 套接字的列表。后者与
netstat -uan
相同。

您引用的内部工具可能将套接字直接绑定到多播地址,这就是多播地址显示在

ss -uan
列表中的原因。然而,这本身并不意味着它已加入多播组。
netstat -ng
的输出告诉你这一点。您的程序绑定到 0.0.0.0,这就是多播地址不显示在那里的原因。

并不是你的程序做错了什么,而是你使用了错误的工具。

© www.soinside.com 2019 - 2024. All rights reserved.