Created
November 28, 2017 15:20
-
-
Save asissuthar/00f8902b94c8285a3e6998a4a985394e to your computer and use it in GitHub Desktop.
Broadcast Data in Network Using UDP Protocol in JAVA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package in.asissuthar; | |
import java.io.IOException; | |
import java.net.*; | |
import java.util.Enumeration; | |
import java.util.List; | |
/** | |
* Created by asissuthar on 11/04/15. | |
*/ | |
public class Broadcast { | |
private DatagramSocket datagramSocket; | |
private InetSocketAddress inetSocketAddress; | |
public Broadcast(int port) throws SocketException { | |
inetSocketAddress = new InetSocketAddress(getAddress(), port); | |
} | |
public void client() throws SocketException { | |
datagramSocket = new DatagramSocket(); | |
datagramSocket.setBroadcast(true); | |
} | |
public void server() throws SocketException { | |
datagramSocket = new DatagramSocket(inetSocketAddress); | |
} | |
public void send(byte[] data) throws IOException { | |
DatagramPacket datagramPacket = new DatagramPacket(data, data.length, inetSocketAddress); | |
datagramSocket.send(datagramPacket); | |
} | |
public DatagramPacket read(int size) throws IOException { | |
byte[] buffer = new byte[size]; | |
DatagramPacket packet = new DatagramPacket(buffer, size); | |
datagramSocket.receive(packet); | |
return packet; | |
} | |
public void close() { | |
if (datagramSocket != null) { | |
datagramSocket.close(); | |
datagramSocket = null; | |
} | |
} | |
public static InetAddress getAddress() throws SocketException { | |
Enumeration<NetworkInterface> interfaces | |
= NetworkInterface.getNetworkInterfaces(); | |
while (interfaces.hasMoreElements()) { | |
NetworkInterface networkInterface = interfaces.nextElement(); | |
if (networkInterface.isLoopback() || !networkInterface.isUp()) { | |
continue; | |
} | |
List<InterfaceAddress> addresses = networkInterface.getInterfaceAddresses(); | |
for (InterfaceAddress address : addresses) { | |
InetAddress inetAddress = address.getBroadcast(); | |
if (inetAddress != null) { | |
return inetAddress; | |
} | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment