List of usage examples for java.net DatagramPacket setAddress
public synchronized void setAddress(InetAddress iaddr)
From source file:Main.java
public static void main(String[] args) throws Exception { int mcPort = 12345; String mcIPStr = "230.1.1.1"; DatagramSocket udpSocket = new DatagramSocket(); InetAddress mcIPAddress = InetAddress.getByName(mcIPStr); byte[] msg = "Hello".getBytes(); DatagramPacket packet = new DatagramPacket(msg, msg.length); packet.setAddress(mcIPAddress); packet.setPort(mcPort);//w w w .j a v a2s. c o m udpSocket.send(packet); System.out.println("Sent a multicast message."); System.out.println("Exiting application"); udpSocket.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { byte[] ary = new byte[128]; DatagramPacket pack = new DatagramPacket(ary, 128); // read/*from w ww .j a va2 s . c o m*/ DatagramSocket sock = new DatagramSocket(1111); sock.receive(pack); String word = new String(pack.getData()); System.out.println("From: " + pack.getAddress() + " Port: " + pack.getPort()); System.out.println(word); sock.close(); // write sock = new DatagramSocket(); pack.setAddress(InetAddress.getByName(args[1])); pack.setData(args[2].getBytes()); pack.setPort(1111); sock.send(pack); sock.close(); }
From source file:UDP0.java
public static void main(String[] args) throws Exception { byte[] ary = new byte[128]; DatagramPacket pack = new DatagramPacket(ary, 128); if (args[0].charAt(0) == 'r') { // read//from w w w. j a v a 2 s.c o m DatagramSocket sock = new DatagramSocket(1111); sock.receive(pack); String word = new String(pack.getData()); System.out.println("From: " + pack.getAddress() + " Port: " + pack.getPort()); System.out.println(word); sock.close(); } else { // write DatagramSocket sock = new DatagramSocket(); pack.setAddress(InetAddress.getByName(args[1])); pack.setData(args[2].getBytes()); pack.setPort(1111); sock.send(pack); sock.close(); } }
From source file:Main.java
public static DatagramPacket getPacket(String msg) throws UnknownHostException { int PACKET_MAX_LENGTH = 1024; byte[] msgBuffer = msg.getBytes(); int length = msgBuffer.length; if (length > PACKET_MAX_LENGTH) { length = PACKET_MAX_LENGTH;/*from w w w .j ava 2s . com*/ } DatagramPacket packet = new DatagramPacket(msgBuffer, length); InetAddress serverIPAddress = InetAddress.getByName("localhost"); packet.setAddress(serverIPAddress); packet.setPort(15900); return packet; }
From source file:SDRecord.java
private static long recordToSocket(DatagramPacket packet, DatagramSocket socket, InetAddress rhost, int destPort) { packet.setPort(destPort);/*from w w w . j a v a 2s.c o m*/ packet.setAddress(rhost); try { socket.send(packet); } catch (IOException e) { e.printStackTrace(); System.exit(5); } return packet.getLength(); }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Returns the network address with which the task manager shall announce itself to the job manager. To determine * the address this method exchanges packets with the job manager. * //from www . j a v a2 s. c om * @param jobManagerAddress * the address of the job manager * @return the address with which the task manager shall announce itself to the job manager * @throws DiscoveryException * thrown if an error occurs during the packet exchange */ public static InetAddress getTaskManagerAddress(final InetAddress jobManagerAddress) throws DiscoveryException { final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER); final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT); InetAddress taskManagerAddress = null; DatagramSocket socket = null; try { socket = new DatagramSocket(); LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT); socket.setSoTimeout(CLIENTSOCKETTIMEOUT); final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE], RESPONSE_PACKET_SIZE); for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) { final DatagramPacket addressRequest = createTaskManagerAddressRequestPacket(magicNumber); addressRequest.setAddress(jobManagerAddress); addressRequest.setPort(discoveryPort); LOG.debug("Sending Task Manager address request to " + addressRequest.getSocketAddress()); socket.send(addressRequest); try { socket.receive(responsePacket); } catch (SocketTimeoutException ste) { LOG.warn("Timeout wainting for task manager address reply. Retrying..."); continue; } if (!isPacketForUs(responsePacket, magicNumber)) { LOG.warn("Received packet which is not destined to this Nephele setup"); continue; } final int packetTypeID = getPacketTypeID(responsePacket); if (packetTypeID != TM_ADDRESS_REPLY_ID) { LOG.warn("Received response of unknown type " + packetTypeID + ", discarding..."); continue; } taskManagerAddress = extractInetAddress(responsePacket); break; } } catch (IOException ioe) { throw new DiscoveryException(StringUtils.stringifyException(ioe)); } finally { if (socket != null) { socket.close(); } } if (taskManagerAddress == null) { throw new DiscoveryException("Unable to obtain task manager address"); } return taskManagerAddress; }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Attempts to retrieve the job managers address in the network through an * IP broadcast. This method should be called by the task manager. * /*from w ww. j a v a 2 s.co m*/ * @return the socket address of the job manager in the network * @throws DiscoveryException * thrown if the job manager's socket address could not be * discovered */ public static InetSocketAddress getJobManagerAddress() throws DiscoveryException { final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER); final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT); InetSocketAddress jobManagerAddress = null; DatagramSocket socket = null; try { final Set<InetAddress> targetAddresses = getBroadcastAddresses(); if (targetAddresses.isEmpty()) { throw new DiscoveryException("Could not find any broadcast addresses available to this host"); } socket = new DatagramSocket(); LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT); socket.setSoTimeout(CLIENTSOCKETTIMEOUT); final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE], RESPONSE_PACKET_SIZE); for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) { final DatagramPacket lookupRequest = createJobManagerLookupRequestPacket(magicNumber); for (InetAddress broadcast : targetAddresses) { lookupRequest.setAddress(broadcast); lookupRequest.setPort(discoveryPort); LOG.debug("Sending discovery request to " + lookupRequest.getSocketAddress()); socket.send(lookupRequest); } try { socket.receive(responsePacket); } catch (SocketTimeoutException ste) { LOG.debug("Timeout wainting for discovery reply. Retrying..."); continue; } if (!isPacketForUs(responsePacket, magicNumber)) { LOG.debug("Received packet which is not destined to this Nephele setup"); continue; } final int packetTypeID = getPacketTypeID(responsePacket); if (packetTypeID != JM_LOOKUP_REPLY_ID) { LOG.debug("Received unexpected packet type " + packetTypeID + ", discarding... "); continue; } final int ipcPort = extractIpcPort(responsePacket); // Replace port from discovery service with the actual RPC port // of the job manager if (USE_IPV6) { // TODO: No connection possible unless we remove the scope identifier if (responsePacket.getAddress() instanceof Inet6Address) { try { jobManagerAddress = new InetSocketAddress( InetAddress.getByAddress(responsePacket.getAddress().getAddress()), ipcPort); } catch (UnknownHostException e) { throw new DiscoveryException(StringUtils.stringifyException(e)); } } else { throw new DiscoveryException(responsePacket.getAddress() + " is not a valid IPv6 address"); } } else { jobManagerAddress = new InetSocketAddress(responsePacket.getAddress(), ipcPort); } LOG.debug("Discovered job manager at " + jobManagerAddress); break; } } catch (IOException ioe) { throw new DiscoveryException(ioe.toString()); } finally { if (socket != null) { socket.close(); } } if (jobManagerAddress == null) { LOG.debug("Unable to discover Jobmanager via IP broadcast"); throw new DiscoveryException("Unable to discover JobManager via IP broadcast!"); } return jobManagerAddress; }
From source file:poisondog.net.udp.SendMission.java
public Void execute(DatagramParameter parameter) throws IOException { DatagramSocket socket = new DatagramSocket(); socket.setReuseAddress(true);//from w ww. j a v a 2 s . c om socket.setBroadcast(parameter.getBroadcast()); if (parameter.getTimeout() > 0) socket.setSoTimeout(parameter.getTimeout()); String data = IOUtils.toString(parameter.getInputStream()); DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length()); packet.setAddress(InetAddress.getByName(parameter.getHost())); if (parameter.getPort() > 0) packet.setPort(parameter.getPort()); socket.send(packet); socket.close(); return null; }
From source file:poisondog.net.udp.DatagramMission.java
public DatagramResponse execute(DatagramParameter parameter) throws IOException { DatagramSocket socket = new DatagramSocket(null); socket.setReuseAddress(true);//from w w w.j ava 2s . co m socket.setBroadcast(parameter.getBroadcast()); if (parameter.getTimeout() > 0) socket.setSoTimeout(parameter.getTimeout()); String data = IOUtils.toString(parameter.getInputStream()); DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length()); packet.setAddress(InetAddress.getByName(parameter.getHost())); packet.setPort(parameter.getPort()); socket.send(packet); DatagramResponse response = new DatagramResponse(parameter.getResponseLength()); DatagramPacket responsePacket = new DatagramPacket(response.getContent(), response.getContent().length); socket.receive(responsePacket); response.setAddress(responsePacket.getAddress().getHostAddress()); response.setPacketLength(responsePacket.getLength()); socket.close(); return response; }
From source file:org.eredlab.g4.ccl.net.ntp.NTPUDPClient.java
/*** * Retrieves the time information from the specified server and port and * returns it. The time is the number of miliiseconds since * 00:00 (midnight) 1 January 1900 UTC, as specified by RFC 1305. * This method reads the raw NTP packet and constructs a <i>TimeInfo</i> * object that allows access to all the fields of the NTP message header. * <p>//from ww w . j a va 2s.co m * @param host The address of the server. * @param port The port of the service. * @return The time value retrieved from the server. * @exception IOException If an error occurs while retrieving the time. ***/ public TimeInfo getTime(InetAddress host, int port) throws IOException { // if not connected then open to next available UDP port if (!isOpen()) { open(); } NtpV3Packet message = new NtpV3Impl(); message.setMode(NtpV3Packet.MODE_CLIENT); message.setVersion(_version); DatagramPacket sendPacket = message.getDatagramPacket(); sendPacket.setAddress(host); sendPacket.setPort(port); NtpV3Packet recMessage = new NtpV3Impl(); DatagramPacket receivePacket = recMessage.getDatagramPacket(); /* * Must minimize the time between getting the current time, * timestamping the packet, and sending it out which * introduces an error in the delay time. * No extraneous logging and initializations here !!! */ TimeStamp now = TimeStamp.getCurrentTime(); // Note that if you do not set the transmit time field then originating time // in server response is all 0's which is "Thu Feb 07 01:28:16 EST 2036". message.setTransmitTime(now); _socket_.send(sendPacket); _socket_.receive(receivePacket); long returnTime = System.currentTimeMillis(); // create TimeInfo message container but don't pre-compute the details yet TimeInfo info = new TimeInfo(recMessage, returnTime, false); return info; }