Java Code Examples for java.net.DatagramPacket#getAddress()
The following examples show how to use
java.net.DatagramPacket#getAddress() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DatagramProcessorImpl.java From DroidDLNA with GNU General Public License v3.0 | 6 votes |
protected IncomingDatagramMessage readRequestMessage(InetAddress receivedOnAddress, DatagramPacket datagram, ByteArrayInputStream is, String requestMethod, String httpProtocol) throws Exception { // Headers UpnpHeaders headers = new UpnpHeaders(is); // Assemble message IncomingDatagramMessage requestMessage; UpnpRequest upnpRequest = new UpnpRequest(UpnpRequest.Method.getByHttpName(requestMethod)); upnpRequest.setHttpMinorVersion(httpProtocol.toUpperCase(Locale.ENGLISH).equals("HTTP/1.1") ? 1 : 0); requestMessage = new IncomingDatagramMessage(upnpRequest, datagram.getAddress(), datagram.getPort(), receivedOnAddress); requestMessage.setHeaders(headers); return requestMessage; }
Example 2
Source File: SampleUDPServer.java From sockslib with Apache License 2.0 | 6 votes |
@Override public void run() { try { socket = new DatagramSocket(port); byte[] receiveBuffer = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length); socket.receive(receivePacket); byte[] data = receivePacket.getData(); DatagramPacket packet = new DatagramPacket(data, receivePacket.getLength(), receivePacket.getAddress(), receivePacket.getPort()); socket.send(packet); socket.close(); socket = null; } catch (java.io.IOException e) { e.printStackTrace(); } }
Example 3
Source File: DatagramProcessorImpl.java From TVRemoteIME with GNU General Public License v2.0 | 6 votes |
protected IncomingDatagramMessage readRequestMessage(InetAddress receivedOnAddress, DatagramPacket datagram, ByteArrayInputStream is, String requestMethod, String httpProtocol) throws Exception { // Headers UpnpHeaders headers = new UpnpHeaders(is); // Assemble message IncomingDatagramMessage requestMessage; UpnpRequest upnpRequest = new UpnpRequest(UpnpRequest.Method.getByHttpName(requestMethod)); upnpRequest.setHttpMinorVersion(httpProtocol.toUpperCase(Locale.ENGLISH).equals("HTTP/1.1") ? 1 : 0); requestMessage = new IncomingDatagramMessage(upnpRequest, datagram.getAddress(), datagram.getPort(), receivedOnAddress); requestMessage.setHeaders(headers); return requestMessage; }
Example 4
Source File: DatagramProcessorImpl.java From TVRemoteIME with GNU General Public License v2.0 | 6 votes |
protected IncomingDatagramMessage readResponseMessage(InetAddress receivedOnAddress, DatagramPacket datagram, ByteArrayInputStream is, int statusCode, String statusMessage, String httpProtocol) throws Exception { // Headers UpnpHeaders headers = new UpnpHeaders(is); // Assemble the message IncomingDatagramMessage responseMessage; UpnpResponse upnpResponse = new UpnpResponse(statusCode, statusMessage); upnpResponse.setHttpMinorVersion(httpProtocol.toUpperCase(Locale.ENGLISH).equals("HTTP/1.1") ? 1 : 0); responseMessage = new IncomingDatagramMessage(upnpResponse, datagram.getAddress(), datagram.getPort(), receivedOnAddress); responseMessage.setHeaders(headers); return responseMessage; }
Example 5
Source File: SsdpDiscovery.java From openhab1-addons with Eclipse Public License 2.0 | 6 votes |
/** * Checks whether a packet does contain all given keywords case insensitive. * If all keywords are contained the IP address of the packet sender will be * returned. * * @param packet * The data packet to be analyzed. * @param keywords * The keywords to be searched for. * @return The IP of the sender if all keywords have been found, null * otherwise. * * @throws IOException */ private String analyzePacket(DatagramPacket packet, String... keywords) throws IOException { logger.debug("Analyzing answer message."); InetAddress addr = packet.getAddress(); ByteArrayInputStream in = new ByteArrayInputStream(packet.getData(), 0, packet.getLength()); String response = IOUtils.toString(in); boolean foundAllKeywords = true; for (String keyword : keywords) { foundAllKeywords &= response.toUpperCase().contains(keyword.toUpperCase()); } if (foundAllKeywords) { logger.debug("Found matching answer."); return addr.getHostAddress(); } logger.debug("Answer did not match."); return null; }
Example 6
Source File: DiscoveryManager.java From zephyr with MIT License | 6 votes |
private void handlePacket(@NonNull DatagramPacket packet) { String received = new String(packet.getData(), 0, packet.getLength(), StandardCharsets.UTF_8); DiscoveryPacket discoveryPacket = mGson.fromJson(received, DiscoveryPacket.class); if (discoveryPacket == null) { return; } @DiscoveredServer.DisabledReason int disabledReason = getDisabledReason(discoveryPacket); InetAddress inetAddress = packet.getAddress(); DiscoveredServer discoveredServer = new DiscoveredServer(inetAddress.getHostAddress(), inetAddress.getHostName(), discoveryPacket.getApiVersion(), discoveryPacket.getTimestamp(), disabledReason); synchronized (mDiscoveredServers) { mDiscoveredServers.put(discoveredServer.getIpAddress(), discoveredServer); ZephyrExecutors.getMainThreadExecutor().execute(() -> { mDiscoveredServersLiveData.setValue(new ArrayList<>(mDiscoveredServers.values())); }); } cleanupDiscoveredServers(); }
Example 7
Source File: HostInfo.java From DeviceConnect-Android with MIT License | 6 votes |
boolean shouldIgnorePacket(DatagramPacket packet) { boolean result = false; if (this.getInetAddress() != null) { InetAddress from = packet.getAddress(); if (from != null) { if (from.isLinkLocalAddress() && (!this.getInetAddress().isLinkLocalAddress())) { // Ignore linklocal packets on regular interfaces, unless this is // also a linklocal interface. This is to avoid duplicates. This is // a terrible hack caused by the lack of an API to get the address // of the interface on which the packet was received. result = true; } if (from.isLoopbackAddress() && (!this.getInetAddress().isLoopbackAddress())) { // Ignore loopback packets on a regular interface unless this is also a loopback interface. result = true; } } } return result; }
Example 8
Source File: DatagramProcessorImpl.java From DroidDLNA with GNU General Public License v3.0 | 6 votes |
protected IncomingDatagramMessage readResponseMessage(InetAddress receivedOnAddress, DatagramPacket datagram, ByteArrayInputStream is, int statusCode, String statusMessage, String httpProtocol) throws Exception { // Headers UpnpHeaders headers = new UpnpHeaders(is); // Assemble the message IncomingDatagramMessage responseMessage; UpnpResponse upnpResponse = new UpnpResponse(statusCode, statusMessage); upnpResponse.setHttpMinorVersion(httpProtocol.toUpperCase(Locale.ENGLISH).equals("HTTP/1.1") ? 1 : 0); responseMessage = new IncomingDatagramMessage(upnpResponse, datagram.getAddress(), datagram.getPort(), receivedOnAddress); responseMessage.setHeaders(headers); return responseMessage; }
Example 9
Source File: UDPServer.java From javase with MIT License | 5 votes |
public static void main(String[] args) { //DatagramSocket socket = null; byte[] bufRecv = null; byte[] bufResp = null; // re-factored with "try with resources" //try { //socket = new DatagramSocket(7778); try (DatagramSocket socket = new DatagramSocket(7778)) { System.out.println("UDP Server bind on 7778 port."); while (true) { bufRecv = new byte[256]; // receive request DatagramPacket packet = new DatagramPacket(bufRecv, bufRecv.length); socket.receive(packet); //bufRecv = packet.getData(); System.out.println("Client says: " + new String(bufRecv)); // figure out the response String respString = new String("OK"); bufResp = respString.getBytes(); // send the response at the client address and port InetAddress address = packet.getAddress(); int port = packet.getPort(); DatagramPacket packetResp = new DatagramPacket(bufResp, bufResp.length, address, port); socket.send(packetResp); } // end while } catch(IOException ioe) { ioe.printStackTrace(); } // finally { // if (socket != null) // socket.close(); // } }
Example 10
Source File: VDatagramSocket.java From finalspeed with GNU General Public License v2.0 | 5 votes |
public void send(DatagramPacket p) throws IOException { TCPTun tun; if (client) { tun = capEnv.tcpManager.getDefaultTcpTun(); if (tun != null) { if (!tun.remoteAddress.getHostAddress().equals(p.getAddress().getHostAddress()) || CapEnv.toUnsigned(tun.remotePort) != p.getPort()) { capEnv.tcpManager.removeTun(tun); capEnv.tcpManager.setDefaultTcpTun(null); } } else { tryConnectTun_Client(p.getAddress(), (short) p.getPort()); tun = capEnv.tcpManager.getDefaultTcpTun(); } } else { tun = capEnv.tcpManager.getTcpConnection_Server(p.getAddress().getHostAddress(), (short) p.getPort()); } if (tun != null) { if (tun.preDataReady) { tun.sendData(p.getData()); } else { throw new IOException("隧道未连接!"); } } else { throw new IOException("隧道不存在! " + " thread " + Route.es.getActiveCount() + " " + p.getAddress() + ":" + p .getPort()); } }
Example 11
Source File: DeviceUpdate.java From beat-link with Eclipse Public License 1.0 | 5 votes |
/** * Constructor sets all the immutable interpreted fields based on the packet content. * * @param packet the device update packet that was received * @param name the type of packet that is being processed, in case a problem needs to be reported * @param length the expected length of the packet */ @SuppressWarnings("WeakerAccess") public DeviceUpdate(DatagramPacket packet, String name, int length) { timestamp = System.nanoTime(); if (packet.getLength() != length) { throw new IllegalArgumentException(name + " packet must be " + length + " bytes long"); } address = packet.getAddress(); packetBytes = new byte[packet.getLength()]; System.arraycopy(packet.getData(), 0, packetBytes, 0, packet.getLength()); deviceName = new String(packetBytes, 11, 20).trim(); preNexusCdj = deviceName.startsWith("CDJ") && deviceName.endsWith("0"); deviceNumber = Util.unsign(packetBytes[33]); }
Example 12
Source File: DatagramSocketAdaptor.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
public void send(DatagramPacket p) throws IOException { synchronized (dc.blockingLock()) { if (!dc.isBlocking()) throw new IllegalBlockingModeException(); try { synchronized (p) { ByteBuffer bb = ByteBuffer.wrap(p.getData(), p.getOffset(), p.getLength()); if (dc.isConnected()) { if (p.getAddress() == null) { // Legacy DatagramSocket will send in this case // and set address and port of the packet InetSocketAddress isa = (InetSocketAddress) dc.remoteAddress(); p.setPort(isa.getPort()); p.setAddress(isa.getAddress()); dc.write(bb); } else { // Target address may not match connected address dc.send(bb, p.getSocketAddress()); } } else { // Not connected so address must be valid or throw dc.send(bb, p.getSocketAddress()); } } } catch (IOException x) { Net.translateException(x); } } }
Example 13
Source File: TcpProvider.java From Daedalus with GNU General Public License v3.0 | 5 votes |
@Override protected void forwardPacket(DatagramPacket outPacket, IpPacket parsedPacket, AbstractDnsServer dnsServer) throws DaedalusVpnService.VpnNetworkException { Socket dnsSocket; try { // Packets to be sent to the real DNS server will need to be protected from the VPN dnsSocket = SocketChannel.open().socket(); service.protect(dnsSocket); SocketAddress address = new InetSocketAddress(outPacket.getAddress(), dnsServer.getPort()); dnsSocket.connect(address, 5000); dnsSocket.setSoTimeout(5000); Logger.info("TcpProvider: Sending DNS query request"); DataOutputStream dos = new DataOutputStream(dnsSocket.getOutputStream()); byte[] packet = processUdpPacket(outPacket, parsedPacket); dos.writeShort(packet.length); dos.write(packet); dos.flush(); if (parsedPacket != null) { dnsIn.add(new TcpProvider.WaitingOnSocketPacket(dnsSocket, parsedPacket)); } else { dnsSocket.close(); } } catch (IOException e) { if (e.getCause() instanceof ErrnoException) { ErrnoException errnoExc = (ErrnoException) e.getCause(); if ((errnoExc.errno == OsConstants.ENETUNREACH) || (errnoExc.errno == OsConstants.EPERM)) { throw new DaedalusVpnService.VpnNetworkException("Cannot send message:", e); } } Log.w(TAG, "handleDnsRequest: Could not send packet to upstream", e); } }
Example 14
Source File: UDPConnManager.java From PacketProxy with Apache License 2.0 | 5 votes |
public void put(DatagramPacket packet) throws Exception { InetSocketAddress addr = new InetSocketAddress(packet.getAddress(), packet.getPort()); UDPConn conn = this.query(addr); if (conn == null) { conn = this.create(addr); conn.getAutomatically(recvQueue); acceptedQueue.put(addr); } conn.put(packet.getData(), 0, packet.getLength()); }
Example 15
Source File: DNSTunnel.java From java-tcp-tunnel with MIT License | 5 votes |
public void run() { String dateStr = sdf.format(new Date()); byte[] buffer = new byte[65536]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); while (true) { try { packet.setData(buffer); packet.setLength(buffer.length); sourceSocket.receive(packet); active = true; InetAddress sourceAddress = packet.getAddress(); int srcPort = packet.getPort(); InetAddress address = InetAddress.getByName(params.getRemoteHost()); String strAddr = toStr(packet); if (params.isPrint()) { System.out.println(dateStr + ": DNS Forwarding " +packet.getLength()+ " bytes " + strAddr + " --> " + address.getHostAddress() + ":" + params.getRemotePort()); } //send client request to server packet.setPort(params.getRemotePort()); packet.setAddress(address); Thread tunnel = new DNSForwarder(packet, sourceSocket, sourceAddress, srcPort, params); tunnel.start(); } catch (Throwable e) { if (params.isPrint()) { String remoteAddr = params.getRemoteHost() + ":" + params.getRemotePort(); String humanRemoteAddr = Utils.mapAddrToHumanReadable(remoteAddr); remoteAddr = remoteAddr + " (" + humanRemoteAddr + ")"; System.err.println(dateStr + ": Failed to connect to remote host (" + remoteAddr + ")"); e.printStackTrace(); } connectionBroken(); } } }
Example 16
Source File: DatagramSocketAdaptor.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
public void send(DatagramPacket p) throws IOException { synchronized (dc.blockingLock()) { if (!dc.isBlocking()) throw new IllegalBlockingModeException(); try { synchronized (p) { ByteBuffer bb = ByteBuffer.wrap(p.getData(), p.getOffset(), p.getLength()); if (dc.isConnected()) { if (p.getAddress() == null) { // Legacy DatagramSocket will send in this case // and set address and port of the packet InetSocketAddress isa = (InetSocketAddress) dc.remoteAddress(); p.setPort(isa.getPort()); p.setAddress(isa.getAddress()); dc.write(bb); } else { // Target address may not match connected address dc.send(bb, p.getSocketAddress()); } } else { // Not connected so address must be valid or throw dc.send(bb, p.getSocketAddress()); } } } catch (IOException x) { Net.translateException(x); } } }
Example 17
Source File: UdpReceiverTask.java From react-native-udp with MIT License | 5 votes |
/** * An infinite loop to block and read data from the socket. */ @Override protected Void doInBackground(Pair<DatagramSocket, UdpReceiverTask.OnDataReceivedListener>... params) { if (params.length > 1) { throw new IllegalArgumentException("This task is only for a single socket/listener pair."); } DatagramSocket socket = params[0].first; OnDataReceivedListener receiverListener = params[0].second; final byte[] buffer = new byte[MAX_UDP_DATAGRAM_LEN]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); while (!isCancelled()) { try { socket.receive(packet); final InetAddress address = packet.getAddress(); final String base64Data = Base64.encodeToString(packet.getData(), packet.getOffset(), packet.getLength(), Base64.NO_WRAP); receiverListener.didReceiveData(base64Data, address.getHostAddress(), packet.getPort()); } catch (IOException ioe) { if (receiverListener != null) { receiverListener.didReceiveError(ioe.getMessage()); } this.cancel(false); } catch (RuntimeException rte) { if (receiverListener != null) { receiverListener.didReceiveRuntimeException(rte); } this.cancel(false); } } return null; }
Example 18
Source File: UDPTestServer.java From sockslib with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws IOException { int port = 5050; if (args.length == 1) { port = Integer.parseInt(args[0]); } DatagramSocket server = new DatagramSocket(port); System.out.println("Listening port at:" + server.getLocalPort()); byte[] receiveBuffer = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length); final String responseMsg = "Yes, I am UDP server"; while (true) { server.receive(receivePacket); String msg = new String(receivePacket.getData(), 0, receivePacket.getLength()); System.out.println("received message:" + msg); if (msg.equals("quit")) { break; } System.out.println("Response:" + responseMsg); byte[] data = responseMsg.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, receivePacket.getAddress(), receivePacket.getPort ()); server.send(packet); } server.close(); }
Example 19
Source File: SnmpResponseHandler.java From JDKSourceCode1.8 with MIT License | 4 votes |
public synchronized void processDatagram(DatagramPacket dgrm) { byte []data = dgrm.getData(); int datalen = dgrm.getLength(); if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINER, SnmpResponseHandler.class.getName(), "action", "processDatagram", "Received from " + dgrm.getAddress().toString() + " Length = " + datalen + "\nDump : \n" + SnmpMessage.dumpHexBuffer(data, 0, datalen)); } try { SnmpMessage msg = new SnmpMessage(); msg.decodeMessage(data, datalen); msg.address = dgrm.getAddress(); msg.port = dgrm.getPort(); // Retreive the PDU factory of the SNMP adaptor to decode the received inform response. // SnmpPduFactory pduFactory = adaptor.getPduFactory(); if (pduFactory == null) { if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(), "processDatagram", "Dropping packet. Unable to find the pdu factory of the SNMP adaptor server"); } } else { SnmpPduPacket snmpProt = (SnmpPduPacket)pduFactory.decodeSnmpPdu(msg); if (snmpProt == null) { if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(), "processDatagram", "Dropping packet. Pdu factory returned a null value"); } } else if (snmpProt instanceof SnmpPduRequest) { SnmpPduRequest pduReq = (SnmpPduRequest)snmpProt; SnmpInformRequest req = snmpq.removeRequest(pduReq.requestId) ; if (req != null) { req.invokeOnResponse(pduReq); } else { if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(), "processDatagram", "Dropping packet. Unable to find corresponding for InformRequestId = " + pduReq.requestId); } } } else { if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(), "processDatagram", "Dropping packet. The packet does not contain an inform response"); } } snmpProt = null ; } } catch (Exception e) { if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(), "processDatagram", "Exception while processsing", e); } } }
Example 20
Source File: SnmpResponseHandler.java From jdk1.8-source-analysis with Apache License 2.0 | 4 votes |
public synchronized void processDatagram(DatagramPacket dgrm) { byte []data = dgrm.getData(); int datalen = dgrm.getLength(); if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINER, SnmpResponseHandler.class.getName(), "action", "processDatagram", "Received from " + dgrm.getAddress().toString() + " Length = " + datalen + "\nDump : \n" + SnmpMessage.dumpHexBuffer(data, 0, datalen)); } try { SnmpMessage msg = new SnmpMessage(); msg.decodeMessage(data, datalen); msg.address = dgrm.getAddress(); msg.port = dgrm.getPort(); // Retreive the PDU factory of the SNMP adaptor to decode the received inform response. // SnmpPduFactory pduFactory = adaptor.getPduFactory(); if (pduFactory == null) { if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(), "processDatagram", "Dropping packet. Unable to find the pdu factory of the SNMP adaptor server"); } } else { SnmpPduPacket snmpProt = (SnmpPduPacket)pduFactory.decodeSnmpPdu(msg); if (snmpProt == null) { if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(), "processDatagram", "Dropping packet. Pdu factory returned a null value"); } } else if (snmpProt instanceof SnmpPduRequest) { SnmpPduRequest pduReq = (SnmpPduRequest)snmpProt; SnmpInformRequest req = snmpq.removeRequest(pduReq.requestId) ; if (req != null) { req.invokeOnResponse(pduReq); } else { if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(), "processDatagram", "Dropping packet. Unable to find corresponding for InformRequestId = " + pduReq.requestId); } } } else { if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(), "processDatagram", "Dropping packet. The packet does not contain an inform response"); } } snmpProt = null ; } } catch (Exception e) { if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(), "processDatagram", "Exception while processsing", e); } } }