List of usage examples for java.net DatagramPacket getAddress
public synchronized InetAddress getAddress()
From source file:Networking.Networking.java
/** * Constructs a new {@see #Networking} object. Sets {@see #state} to * {@see Networking.NetworkState#NOT_CONNECTED}, initializes {@see #udpInData} * as array of 512 bytes. Sets {@see #playerPortUDP} to value defined in * {@see edu.cvut.vorobvla.bap.BapPorts#PLAYER_PORT} and initializes * {@see udpSocket} with this value as constructor parameter (a port to * bind with this socket). If initialization fails * ({@code SocketException} occurs) increments {@see #playerPortUDP} and * attempts to initialize {@see udpSocket} with parameter {@see #playerPortUDP}. * Proceeds like this until initialization succeeds or until {@see #playerPortUDP} * reaches {@see edu.cvut.vorobvla.bap.BapPorts#PLAYER_PORT}{@code + } * {@see edu.cvut.vorobvla.bap.BapPorts#PLAYER_PORT_RANGE}{@code - 1}. * Initializes {@see networkListener} as an anonymous {@code Thread} child * with overridden {@code run()} method. * <p> The {@code run()} method//from w ww .java2s . co m * the greatest part of the network protocol (waits for * {@see edu.cvut.vorobvla.bap.BapMessages#MSG_CALL_FOR_PLAYERS}, processes it * and calls {@see establishConnectionWithModerator} and {@see recvOpts}). * <p>Constructor of {@see #Networking} proceeds with setting {@see #gameListener} * to {@code null}, {@see #broadcastLatestTimestamp} to {@code 0} and * initializing {@see #parser}. * * @throws SocketException if all attempts to initialize {@see udpSocket} * were unsuccessful. */ private Networking() throws SocketException { state = NetworkState.NOT_CONNECTED; this.playerPortUDP = BapPorts.PLAYER_PORT; // identity = Player.getInstance().getName(); udpInData = new byte[512]; while (udpSocket == null) {//may be bug try { udpSocket = new DatagramSocket(playerPortUDP); } catch (SocketException ex) { if (playerPortUDP < BapPorts.PLAYER_PORT + BapPorts.PLAYER_PORT_RANGE) { Logger.getLogger(Networking.class.getName()).log(Level.INFO, "bad UDP port " + playerPortUDP + ". trying another...", "bad UDP port " + playerPortUDP + ". trying another..."); playerPortUDP++; } else { throw new SocketException("no suttable UDP port"); //Logger.getLogger(Networking.class.getName()).log(Level.SEVERE, null, "no suttable UDP port"); //break; } } } networkListener = new Thread() { @Override public void run() { try { // System.out.println("Start listening to UDP broadcast on" // + udpSocket.getLocalSocketAddress().toString()); DatagramPacket initMsgFromModerator = recvUDP(); String msg = new String(initMsgFromModerator.getData()); if (!msg.split(":")[0].matches(BapMessages.MSG_CALL_FOR_PLAYERS)) { System.err.println("wrong message. got '" + msg + "' while '" + BapMessages.MSG_CALL_FOR_PLAYERS + "' expexted"); return; } System.out.println("RECEVED: " + msg); //get the moderator's IP from the pachage and the port that is listen by it from the message establishConnectionWithModerator(initMsgFromModerator.getAddress(), Integer.parseInt(msg.split(BapMessages.FIELD_DELIM)[1].replaceAll("\\D", ""))); recvOpts(); } catch (IOException ex) { Logger.getLogger(Networking.class.getName()).log(Level.SEVERE, null, ex); System.err.println("exception while establishing connection"); } } }; gameListener = null; parser = new JSONParser(); broadcastLatestTimestamp = 0; // establishConnectionWithModerator(); }
From source file:net.spfbl.dnsbl.QueryDNSBL.java
/** * Inicializao do servio.// w w w . j ava2 s. c o m */ @Override public void run() { try { Server.logInfo("listening DNSBL on UDP port " + PORT + "."); while (continueListenning()) { try { byte[] receiveData = new byte[1024]; DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length); SERVER_SOCKET.receive(packet); if (continueListenning()) { long time = System.currentTimeMillis(); Connection connection = pollConnection(); if (connection == null) { InetAddress ipAddress = packet.getAddress(); String result = "TOO MANY CONNECTIONS\n"; Server.logQueryDNSBL(time, ipAddress, null, result); } else { try { connection.process(packet, time); } catch (IllegalThreadStateException ex) { // Houve problema na liberao do processo. InetAddress ipAddress = packet.getAddress(); String result = "ERROR: FATAL\n"; Server.logError(ex); Server.logQueryDNSBL(time, ipAddress, null, result); offer(connection); } } } } catch (SocketException ex) { // Conexo fechada externamente pelo mtodo close(). } } } catch (Exception ex) { Server.logError(ex); } finally { Server.logInfo("querie DNSBL server closed."); } }
From source file:org.rifidi.emulator.io.comm.ip.udp.UDPCommunicationIncomingMessageHandler.java
/** * The main logic of the monitor. Reads in data from the client socket until * the client socket is closed/disconnected. * // w ww .java2 s. com * @see java.lang.Runnable#run() */ public void run() { /* Create a Datagram packet to hold the recieved message */ DatagramPacket pack = new DatagramPacket(new byte[PACKET_SIZE], PACKET_SIZE); /* Should the loop keep running? */ boolean keepRunning = true; /* This part loops until we catch an exception */ while (keepRunning) { /* receive messages on the socket */ try { System.out.println("Attempting to recieve a packet"); newSock.receive(pack); System.out.println("RECIEVED A PACKET OMG"); } catch (IOException e) { e.printStackTrace(); logger.warn(e.getMessage()); } /* put messages into the buffer */ if (pack.getData() != null) { try { // List<byte[]> listOfBytes = this.host.getProtocol() // .removeProtocol(pack.getData()); // for (byte[] b : listOfBytes) { this.host.getReceiveBuffer().addToBuffer(pack.getData()); this.host.setRemoteIPAddress(pack.getAddress().getHostAddress()); this.host.setRemotePort(pack.getPort()); // } } catch (DataBufferInterruptedException e) { /* Thrown because socket was interrupted */ logger.warn(e.getMessage()); keepRunning = false; } // catch (ProtocolValidationException e) { // /* Thrown because of a problem with the protocol */ // logger.warn(e.getMessage()); // } } } }
From source file:org.achartengine.chartdemo.demo.ChartDemo.java
/** * Called when the activity is first created. *//*from w ww.jav a2 s . c o m*/ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.main); mAppPreferences = new AppPreferences(getApplicationContext()); SmartConnectUtils.setProtraitOrientationEnabled(this); mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe); mSwipeRefreshLayout.setColorScheme(android.R.color.holo_red_light, android.R.color.holo_blue_light, android.R.color.holo_green_light, android.R.color.holo_green_light); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mSwipeRefreshLayout.setRefreshing(true); Log.d(TAG, "Refreshing Number"); (new Handler()).postDelayed(new Runnable() { @Override public void run() { mSwipeRefreshLayout.setRefreshing(false); image_details.clear(); listProduct.clear(); mAdapter.notifyDataSetChanged(); } }, 2000); } }); listView_Node = (ListView) findViewById(R.id.listView_Node); /*1. add listview adapter*/ mAdapter = new ItemListBaseAdapter(this, image_details); listView_Node.setAdapter(mAdapter); listView_Node.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> a, View v, int position, long id) { String productType = null; Object o = listView_Node.getItemAtPosition(position); ItemDetails obj_itemDetails = (ItemDetails) o; udpBroadcast.close(); dataSource = obj_itemDetails.getName(); for (Map<String, String> tmp : listProduct) { if (tmp.containsKey(dataSource)) productType = tmp.get(dataSource); } //If id1=2, it means elock; then id1=1, it means wps /* if (productType.equals("2")) { Intent intent = new Intent(ChartDemo.this, ElockActivity.class); intent.putExtra("dataSource", dataSource); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else if (productType.equals("1")) { Intent intent = new Intent(ChartDemo.this, NumChartActivity.class); intent.putExtra("dataSource", dataSource); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else if (productType.equals("4")) { Intent intent = new Intent(ChartDemo.this, ScaleActivity.class); intent.putExtra("dataSource", dataSource); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else*/ if (productType.equals("2")) { Intent intent = new Intent(ChartDemo.this, PlugActivity.class); intent.putExtra("dataSource", dataSource); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } } }); /*2. add a handler*/ mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case AddNode: { Map<String, String> listItem = new HashMap<String, String>(); listItem.put(msg.obj.toString(), String.valueOf(msg.arg1)); listProduct.add(listItem); mAdapter.notifyDataSetChanged(); break; } case START_SEARCH: { if (udpBroadcast.isClosed()) udpBroadcast.open(); udpBroadcast.receive(); mHandler.sendEmptyMessageDelayed(START_SEARCH, DELAY); break; } } } }; /*3. Create one udpbroadcast object*/ udpBroadcast = new udpbroadcast() { private String getDataSource(DatagramPacket datagramPacket) { int i; String data = new String(datagramPacket.getData(), 2, 9); /*check the length of name*/ for (i = 0; i < 9; i++) { if (datagramPacket.getData()[2 + i] == 0) break; } String ssid = new String(datagramPacket.getData(), 2, i); return ssid; } private boolean IsExsits(String SSID) { for (ItemDetails tmp : image_details) { Log.d(TAG, "list node is " + SSID); if (tmp.getName().equals(SSID)) return true; } return false; } /* * typedef struct s_msg_temp_keepalive { * uint8_t id0; * uint8_t id1; * uint8_t name[9]; * uint8_t type; * } t_msg_temp_keepalive; * For PWS: keepalive:id0=0, id1=1; * data report: id0=0, id1=3; * For E-lock: keepalive: id0=0, id1=2; * * For E-scale: keepalive: id0=0, id1=4; * * * * */ @Override public void onReceived(List<DatagramPacket> packets) { for (DatagramPacket packet : packets) { String data = new String(packet.getData(), 0, packet.getLength()); /*Parse ssid*/ if (packet.getData()[0] == 0 && (packet.getData()[1] == 1 || packet.getData()[1] == 2 || packet.getData()[1] == 4 || packet.getData()[1] == 5)) { String tmp_ssid = getDataSource(packet); Log.d(TAG, "Get alive report: " + tmp_ssid); if (IsExsits(tmp_ssid) == false) { Log.d(TAG, "Not exist need add it"); //For JB version it has an extra quote. so need just ignore it. mAppPreferences.setParameter(tmp_ssid, packet.getAddress().toString().substring(1)); ItemDetails item_details = new ItemDetails(); item_details.setName(tmp_ssid); if (packet.getData()[1] == 2) { item_details.setItemDescription("air conditon"); if (packet.getData()[11] == 2) { item_details.setPrice("camera&temperature"); } else if (packet.getData()[11] == 3) { item_details.setPrice("Location: toilet"); } item_details.setImageNumber(2); } image_details.add(item_details); Message msg = mHandler.obtainMessage(AddNode); msg.obj = tmp_ssid; msg.arg1 = packet.getData()[1]; mHandler.sendMessage(msg); } else { } } } } }; /*4. Start auto update search*/ startSearch(); }
From source file:us.nineworlds.serenity.core.services.GDMService.java
@Override protected void onHandleIntent(Intent intent) { try {// ww w . ja va 2 s . c om DatagramSocket socket = new DatagramSocket(32414); socket.setBroadcast(true); String data = "M-SEARCH * HTTP/1.1\r\n\r\n"; DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), useMultiCastAddress(), 32414); // DatagramPacket packet = new DatagramPacket(data.getBytes(), // data.length(), getBroadcastAddress(), 32414); socket.send(packet); Log.d("GDMService", "Search Packet Broadcasted"); byte[] buf = new byte[256]; packet = new DatagramPacket(buf, buf.length); socket.setSoTimeout(2000); boolean listening = true; while (listening) { try { socket.receive(packet); String packetData = new String(packet.getData()); if (packetData.contains("HTTP/1.0 200 OK")) { Log.d("GDMService", "PMS Packet Received"); // Broadcast Received Packet Intent packetBroadcast = new Intent(GDMService.MSG_RECEIVED); packetBroadcast.putExtra("data", packetData); packetBroadcast.putExtra("ipaddress", packet.getAddress().toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(packetBroadcast); } } catch (SocketTimeoutException e) { Log.d("GDMService", "Socket Timeout"); socket.close(); listening = false; Intent socketBroadcast = new Intent(GDMService.SOCKET_CLOSED); LocalBroadcastManager.getInstance(this).sendBroadcast(socketBroadcast); } } } catch (IOException e) { Log.e("GDMService", e.toString()); } }
From source file:net.spfbl.dns.QueryDNS.java
/** * Inicializao do servio.//from w w w .ja va 2s.com */ @Override public void run() { try { Server.logInfo("listening DNS on UDP port " + PORT + "."); while (continueListenning()) { try { byte[] receiveData = new byte[1024]; DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length); SERVER_SOCKET.receive(packet); if (continueListenning()) { long time = System.currentTimeMillis(); Connection connection = pollConnection(); if (connection == null) { InetAddress ipAddress = packet.getAddress(); String result = "TOO MANY CONNECTIONS\n"; Server.logQueryDNSBL(time, ipAddress, null, result); } else { try { connection.process(packet, time); } catch (IllegalThreadStateException ex) { // Houve problema na liberao do processo. InetAddress ipAddress = packet.getAddress(); String result = "ERROR: FATAL\n"; Server.logError(ex); Server.logQueryDNSBL(time, ipAddress, null, result); offer(connection); } } } } catch (SocketException ex) { // Conexo fechada externamente pelo mtodo close(). } } } catch (Exception ex) { Server.logError(ex); } finally { Server.logInfo("querie DNS server closed."); } }
From source file:org.echocat.jomon.net.dns.DnsServer.java
public void serveUDP(InetSocketAddress address) { try {/*from w w w.ja va2 s .c om*/ final DatagramSocket sock = new DatagramSocket(address.getPort(), address.getAddress()); synchronized (_closeables) { _closeables.add(sock); } final short udpLength = 512; final byte[] in = new byte[udpLength]; final DatagramPacket indp = new DatagramPacket(in, in.length); DatagramPacket outdp = null; while (!currentThread().isInterrupted()) { indp.setLength(in.length); receive(sock, indp); final Message query; byte[] response; try { query = new Message(in); response = generateReply(query, in, indp.getLength(), null); if (response == null) { continue; } } catch (final IOException ignored) { response = formerrMessage(in); } if (outdp == null) { outdp = new DatagramPacket(response, response.length, indp.getAddress(), indp.getPort()); } else { outdp.setData(response); outdp.setLength(response.length); outdp.setAddress(indp.getAddress()); outdp.setPort(indp.getPort()); } sock.send(outdp); } } catch (final InterruptedIOException ignored) { currentThread().interrupt(); } catch (final IOException e) { LOG.warn("serveUDP(" + addrport(address.getAddress(), address.getPort()) + ")", e); } }
From source file:udpserver.UDPui.java
private void tempReceiveUDP() { background = new Runnable() { public void run() { try { serverSocket = new DatagramSocket(9876); } catch (SocketException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); }/*w w w.ja v a2 s .com*/ // while (true) { // byte[] receiveData = new byte[1024]; // DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); // if (!new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()).equals("")) { // int count = 1; while (true) { try { byte[] receiveData = new byte[total_byte]; byte[] sendData = new byte[32]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String message = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); // String word = serverSocket.getInetAddress().toString(); // Integer count = counting.get(word); // if (count == null) { // counting.put(word, 1); // } // else { // counting.put(word, count + 1); // } boolean looprun = true; String word = receivePacket.getAddress().getHostAddress(); System.out.println(word); // System.out.println(message); while (looprun) { if (message.contains("&")) { message = message.substring(message.indexOf("&") + 1); Integer count = counting.get(word); if (count == null) { counting.put(word, 2); } else { counting.put(word, count + 1); } // System.out.println(count + ":" + message); } else { looprun = false; } } if (message.equals("end")) { valuePane.setCaretPosition(valuePane.getDocument().getLength()); //send back to mobile InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = counting.get(word) + ""; sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); //end send back to mobile // count = 1; // break; counting.remove(word); } else if (available) { // series.add(count, Double.parseDouble(message)); // valuePane.setText(valuePane.getText().toString() + count + ":" + message + "\n"); // valuePane.setCaretPosition(valuePane.getDocument().getLength()); // count++; } } catch (IOException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); } } // } // } } }; backgroundProcess = new Thread(background); }
From source file:org.restcomm.sbc.media.MediaZone.java
public void send(DatagramPacket dgram) throws IOException { if (dgram == null) return;//from w ww .j a v a 2s . c o m dgram.setAddress(mediaZonePeer.getOriginalAddress()); dgram.setPort(mediaZonePeer.getOriginalRtpPort()); //dgram.setData(mediaZonePeer.encodeRTP(dgram.getData(), 0, dgram.getLength()), 0, dgram.getLength() ); //LOG.trace("--->("+this.mediaType+", "+this.direction+") LocalProxy "+proxyHost+":"+proxyPort+"/"+dgram.getAddress()+":"+dgram.getPort()+"["+dgram.getLength()+"]"); //LOG.trace("---> via socket "+toPrint(socket)); if (dgram.getData().length > 8) { if (logCounter == rtpCountLog) { RawPacket rtp = new RawPacket(dgram.getData(), 0, dgram.getLength()); LOG.trace("--->[PayloadType " + rtp.getPayloadType() + "](" + this.mediaType + ", " + this.direction + ") LocalProxy " + proxyHost + ":" + proxyPort + "/" + dgram.getAddress() + ":" + dgram.getPort() + "[" + dgram.getLength() + "]"); logCounter = 0; } } else { LOG.warn("--->[PayloadType ?](" + this.mediaType + ", " + this.direction + ") LocalProxy " + proxyHost + ":" + proxyPort + "/" + dgram.getAddress() + ":" + dgram.getPort() + "[" + dgram.getLength() + "]"); } packetsSentCounter++; socket.send(dgram); }
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. * // ww w . j a v a 2 s. c o 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; }