java与网络(IPv4组播)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java与网络(IPv4组播)相关的知识,希望对你有一定的参考价值。


1. 接收组播包

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class MulticastReceiver

public static void main(String[] args)
InetAddress group = null;
int port = 0;

try
group = InetAddress.getByName(args[0]);
port = Integer.parseInt(args[1]);
catch (Exception e)
System.err.println("Usage: multicast_address port");
System.exit(1);


MulticastSocket ms = null;
try
ms = new MulticastSocket(port);
ms.joinGroup(group);

System.out.println("waiting for multicast test data");

byte[] buffer = new byte[8192];
while (true)
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ms.receive(dp);
String str = new String(dp.getData(), "UTF-8");
System.out.println(str);

catch (Exception e)
e.printStackTrace();
finally
if (ms != null)
try
ms.leaveGroup(group);
ms.close();
catch (Exception e)
e.printStackTrace();




2. 发送组播包

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

public class MulticastSender

public static void main(String[] args)
InetAddress addr = null;
int port = 0;
byte ttl = (byte) 1;

try
addr = InetAddress.getByName(args[0]);
port = Integer.parseInt(args[1]);
if (args.length > 2)
ttl = (byte) Integer.parseInt(args[2]);

catch (Exception e)
e.printStackTrace();
System.err.println("Usage: multicast_address port ttl");
System.exit(1);


byte[] data = "Heres some multicast test data\\r\\n".getBytes();
DatagramPacket dp = new DatagramPacket(data, data.length, addr, port);

//指定组播流输出的接口
InetAddress eth = null;
try
eth = InetAddress.getByName("192.168.1.102"); //接口上的IP
catch (UnknownHostException e)
e.printStackTrace();


try (MulticastSocket ms = new MulticastSocket())
ms.setInterface(eth);
ms.setTimeToLive(ttl);
ms.joinGroup(addr);
for (int i = 1; i < 100; i++)
ms.send(dp);

System.out.println("Multicast test data sending complete.");
catch (Exception e)
e.printStackTrace();



以上是关于java与网络(IPv4组播)的主要内容,如果未能解决你的问题,请参考以下文章

BGP特性(8)

HuaWei ❀ IPv4组播地址梳理

IP通信类型与地址类型

IPV4简单分类

组播技术基础

Python 实现udp组播