List of usage examples for java.net DatagramPacket getAddress
public synchronized InetAddress getAddress()
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:ChatClient.java
public static void main(String[] args) throws Exception { int PORT = 4000; byte[] buf = new byte[1000]; DatagramPacket dgp = new DatagramPacket(buf, buf.length); DatagramSocket sk;// w ww . j a v a2 s. co m sk = new DatagramSocket(PORT); System.out.println("Server started"); while (true) { sk.receive(dgp); String rcvd = new String(dgp.getData(), 0, dgp.getLength()) + ", from address: " + dgp.getAddress() + ", port: " + dgp.getPort(); System.out.println(rcvd); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String outMessage = stdin.readLine(); buf = ("Server say: " + outMessage).getBytes(); DatagramPacket out = new DatagramPacket(buf, buf.length, dgp.getAddress(), dgp.getPort()); sk.send(out); } }
From source file:UDPReceive.java
public static void main(String args[]) { try {//w w w.j a v a2s . co m int port = 90; // Create a socket to listen on the port. DatagramSocket dsocket = new DatagramSocket(port); // Create a buffer to read datagrams into. If a // packet is larger than this buffer, the // excess will simply be discarded! byte[] buffer = new byte[2048]; // Create a packet to receive data into the buffer DatagramPacket packet = new DatagramPacket(buffer, buffer.length); // Now loop forever, waiting to receive packets and printing them. while (true) { // Wait to receive a datagram dsocket.receive(packet); // Convert the contents to a string, and display them String msg = new String(buffer, 0, packet.getLength()); System.out.println(packet.getAddress().getHostName() + ": " + msg); // Reset the length of the packet before reusing it. packet.setLength(buffer.length); } } catch (Exception e) { System.err.println(e); } }
From source file:UDPReceive.java
public static void main(String args[]) { try {//from w w w . j av a 2 s . c o m if (args.length != 1) throw new IllegalArgumentException("Wrong number of args"); // Get the port from the command line int port = Integer.parseInt(args[0]); // Create a socket to listen on the port. DatagramSocket dsocket = new DatagramSocket(port); // Create a buffer to read datagrams into. If anyone sends us a // packet containing more than will fit into this buffer, the // excess will simply be discarded! byte[] buffer = new byte[2048]; // Create a packet to receive data into the buffer DatagramPacket packet = new DatagramPacket(buffer, buffer.length); // Now loop forever, waiting to receive packets and printing them. for (;;) { // Wait to receive a datagram dsocket.receive(packet); // Decode the bytes of the packet to characters, using the // UTF-8 encoding, and then display those characters. String msg = new String(buffer, 0, packet.getLength(), "UTF-8"); System.out.println(packet.getAddress().getHostName() + ": " + msg); // Reset the length of the packet before reusing it. // Prior to Java 1.1, we'd just create a new packet each time. packet.setLength(buffer.length); } } catch (Exception e) { System.err.println(e); System.err.println(usage); } }
From source file:ChatClient.java
public static void main(String[] args) throws Exception { DatagramSocket s = new DatagramSocket(); byte[] buf = new byte[1000]; DatagramPacket dp = new DatagramPacket(buf, buf.length); InetAddress hostAddress = InetAddress.getByName("localhost"); while (true) {//from www. jav a2 s. co m BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String outMessage = stdin.readLine(); if (outMessage.equals("bye")) break; String outString = "Client say: " + outMessage; buf = outString.getBytes(); DatagramPacket out = new DatagramPacket(buf, buf.length, hostAddress, 9999); s.send(out); s.receive(dp); String rcvd = "rcvd from " + dp.getAddress() + ", " + dp.getPort() + ": " + new String(dp.getData(), 0, dp.getLength()); System.out.println(rcvd); } }
From source file:Main.java
public static void displayPacketDetails(DatagramPacket packet) { byte[] msgBuffer = packet.getData(); int length = packet.getLength(); int offset = packet.getOffset(); int remotePort = packet.getPort(); InetAddress remoteAddr = packet.getAddress(); String msg = new String(msgBuffer, offset, length); System.out.println(/*from www. ja va2s. c o m*/ "Received a packet:[IP Address=" + remoteAddr + ", port=" + remotePort + ", message=" + msg + "]"); }
From source file:Main.java
public static void displayPacketDetails(DatagramPacket packet) { byte[] msgBuffer = packet.getData(); int length = packet.getLength(); int offset = packet.getOffset(); int remotePort = packet.getPort(); InetAddress remoteAddr = packet.getAddress(); String msg = new String(msgBuffer, offset, length); System.out.println("[Server at IP Address=" + remoteAddr + ", port=" + remotePort + "]: " + msg); }
From source file:gravity.android.discovery.DiscoveryClient.java
public static ArrayList<DiscoveryServerInfo> findServer(WifiManager mWifi, int port, String token) { ArrayList<DiscoveryServerInfo> ret = new ArrayList<DiscoveryServerInfo>(); try {/* ww w.j a v a2s.c om*/ DatagramSocket clientSocket = new DatagramSocket(); clientSocket.setBroadcast(true); InetAddress IPAddress = Utils.getBroadcastAddress(mWifi); Log.v("DISCOVERY_CLIENT", "broadcast addr " + IPAddress.getHostAddress()); byte[] receiveData = new byte[2048]; byte[] sendData = new byte[128]; sendData = token.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); Log.v("DISCOVERY_CLIENT", "sent " + token); clientSocket.send(sendPacket); long t1 = System.currentTimeMillis(); while (System.currentTimeMillis() - t1 <= 4000) // 4 secondi { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); try { clientSocket.setSoTimeout(500); clientSocket.receive(receivePacket); if (receivePacket.getAddress() != null && receivePacket.getAddress().getHostAddress() != null) { String discovered_name, discovered_ip; int discovered_port; String received = new String(receivePacket.getData()); if (received != null) { received = received.trim().substring(0, receivePacket.getLength()).trim(); Log.d("Recieved Msg Packet:", received); //StringTokenizer st = new StringTokenizer(received, ","); //Gravity Code JSONObject recievedJson = new JSONObject(received); try { //discovered_name = st.nextToken(); discovered_name = recievedJson.getString("name"); //Gravity code discovered_ip = receivePacket.getAddress().getHostAddress(); //discovered_port = Integer.parseInt(st.nextToken()); discovered_port = recievedJson.getInt("port_to_share"); //Gravity code Log.v("DISCOVERY_CLIENT", "discovered " + discovered_name + ", " + discovered_ip + ":" + discovered_port); boolean add = true; if (ret.size() > 0) { for (DiscoveryServerInfo dsi : ret) { if (dsi != null && dsi.ip.equals(discovered_ip)) { add = false; break; } } } if (add) { ret.add(new DiscoveryServerInfo(discovered_name, discovered_ip, discovered_port)); } } catch (NoSuchElementException nsee) { Log.v("DISCOVERY_CLIENT", nsee.getLocalizedMessage()); } } } } catch (SocketTimeoutException tex) { /* ignored */ } } clientSocket.close(); } catch (Exception ex) { ex.printStackTrace(); Log.e("DISCOVERY_CLIENT", ex.toString()); } return ret; }
From source file:org.cc86.MMC.client.Main.java
public static String serverDiscovery() { String res = "0.0.0.0"; DatagramSocket c;//w ww. j a v a2 s. c o m // Find the server using UDP broadcast try { //Open a random port to send the package c = new DatagramSocket(); c.setBroadcast(true); byte[] sendData = "DISCOVER_MMC_REQUEST".getBytes(); //Try the 255.255.255.255 first try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 0xCC86); c.send(sendPacket); l.info("Request packet sent to: 255.255.255.255 (DEFAULT)"); } catch (Exception e) { } // Broadcast the message over all the network interfaces Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; // Don't want to broadcast to the loopback interface } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); if (broadcast == null) { continue; } // Send the broadcast package! try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888); c.send(sendPacket); } catch (Exception e) { } l.info("Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName()); } } l.info("Done looping over all network interfaces. Now waiting for a reply!"); //Wait for a response byte[] recvBuf = new byte[15000]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); c.receive(receivePacket); //We have a response l.info("Broadcast response from server: " + receivePacket.getAddress().getHostAddress()); //Check if the message is correct String message = new String(receivePacket.getData()).trim(); if (message.equals("DISCOVER_MMC_RESPONSE")) { //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller) res = (receivePacket.getAddress() + "").substring(1); } //Close the port! c.close(); } catch (IOException ex) { } return res; }
From source file:net.pms.network.UPNPHelper.java
/** * Starts up two threads: one to broadcast UPnP ALIVE messages and another * to listen for responses. //from w w w .j ava 2s . c om * * @throws IOException Signals that an I/O exception has occurred. */ public static void listen() throws IOException { Runnable rAlive = new Runnable() { @Override public void run() { int delay = 10000; while (true) { sleep(delay); sendAlive(); // The first delay for sending an ALIVE message is 10 seconds, // the second delay is for 20 seconds. From then on, all other // delays are for 180 seconds. switch (delay) { case 10000: delay = 20000; break; case 20000: delay = 180000; break; } } } }; aliveThread = new Thread(rAlive, "UPNP-AliveMessageSender"); aliveThread.start(); Runnable r = new Runnable() { @Override public void run() { boolean bindErrorReported = false; while (true) { MulticastSocket multicastSocket = null; try { // Use configurable source port as per http://code.google.com/p/ps3mediaserver/issues/detail?id=1166 multicastSocket = new MulticastSocket(configuration.getUpnpPort()); if (bindErrorReported) { logger.warn( "Finally, acquiring port " + configuration.getUpnpPort() + " was successful!"); } NetworkInterface ni = NetworkConfiguration.getInstance().getNetworkInterfaceByServerName(); try { // Setting the network interface will throw a SocketException on Mac OSX // with Java 1.6.0_45 or higher, but if we don't do it some Windows // configurations will not listen at all. if (ni != null) { multicastSocket.setNetworkInterface(ni); } else if (PMS.get().getServer().getNetworkInterface() != null) { multicastSocket.setNetworkInterface(PMS.get().getServer().getNetworkInterface()); logger.trace("Setting multicast network interface: " + PMS.get().getServer().getNetworkInterface()); } } catch (SocketException e) { // Not setting the network interface will work just fine on Mac OSX. } multicastSocket.setTimeToLive(4); multicastSocket.setReuseAddress(true); InetAddress upnpAddress = getUPNPAddress(); multicastSocket.joinGroup(upnpAddress); while (true) { byte[] buf = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(buf, buf.length); multicastSocket.receive(receivePacket); String s = new String(receivePacket.getData()); InetAddress address = receivePacket.getAddress(); if (s.startsWith("M-SEARCH")) { String remoteAddr = address.getHostAddress(); int remotePort = receivePacket.getPort(); if (configuration.getIpFiltering().allowed(address)) { logger.trace( "Receiving a M-SEARCH from [" + remoteAddr + ":" + remotePort + "]"); if (StringUtils.indexOf(s, "urn:schemas-upnp-org:service:ContentDirectory:1") > 0) { sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:service:ContentDirectory:1"); } if (StringUtils.indexOf(s, "upnp:rootdevice") > 0) { sendDiscover(remoteAddr, remotePort, "upnp:rootdevice"); } if (StringUtils.indexOf(s, "urn:schemas-upnp-org:device:MediaServer:1") > 0) { sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:device:MediaServer:1"); } if (StringUtils.indexOf(s, "ssdp:all") > 0) { sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:device:MediaServer:1"); } if (StringUtils.indexOf(s, PMS.get().usn()) > 0) { sendDiscover(remoteAddr, remotePort, PMS.get().usn()); } } } else if (s.startsWith("NOTIFY")) { String remoteAddr = address.getHostAddress(); int remotePort = receivePacket.getPort(); logger.trace("Receiving a NOTIFY from [" + remoteAddr + ":" + remotePort + "]"); } } } catch (BindException e) { if (!bindErrorReported) { logger.error("Unable to bind to " + configuration.getUpnpPort() + ", which means that PMS will not automatically appear on your renderer! " + "This usually means that another program occupies the port. Please " + "stop the other program and free up the port. " + "PMS will keep trying to bind to it...[" + e.getMessage() + "]"); } bindErrorReported = true; sleep(5000); } catch (IOException e) { logger.error("UPNP network exception", e); sleep(1000); } finally { if (multicastSocket != null) { // Clean up the multicast socket nicely try { InetAddress upnpAddress = getUPNPAddress(); multicastSocket.leaveGroup(upnpAddress); } catch (IOException e) { } multicastSocket.disconnect(); multicastSocket.close(); } } } } }; listenerThread = new Thread(r, "UPNPHelper"); listenerThread.start(); }