Java Code Examples for java.net.DatagramPacket#getPort()

The following examples show how to use java.net.DatagramPacket#getPort() . 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: UDPServer.java    From code with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) {
    try {

        DatagramSocket socket = new DatagramSocket(65001);
        byte[] buff = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buff, buff.length);
        // 接收客户端发送的内容,封装到DatagramPacket中
        socket.receive(packet);

        byte[] data = packet.getData();
        // 将字节流转为字符串(输出)
        String content = new String(data, 0, packet.getLength());
        System.out.println(content);
        // 将字符串转为字节流(回写给客户端)
        byte[] bytes = String.valueOf(content.length()).getBytes();

        DatagramPacket packetToClient = new DatagramPacket(bytes, bytes.length, packet.getAddress(), packet.getPort());

        socket.send(packetToClient);

    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example 2
Source File: UDPSlaveTerminal.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void run() {
    do {
        try {
            // 1. pickup the message and corresponding request
            byte[] message = (byte[]) m_SendQueue.take();
            DatagramPacket req = (DatagramPacket) m_Requests
                    .remove(new Integer(ModbusUtil.registersToInt(message)));
            // 2. create new Package with corresponding address and port
            DatagramPacket res = new DatagramPacket(message, message.length, req.getAddress(), req.getPort());
            m_Socket.send(res);
            logger.trace("Sent package from queue");
        } catch (Exception ex) {
            DEBUG: ex.printStackTrace();
        }
    } while (m_Continue || !m_SendQueue.isEmpty());
}
 
Example 3
Source File: DatagramProcessorImpl.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
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: SampleUDPServer.java    From sockslib with Apache License 2.0 6 votes vote down vote up
@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 5
Source File: SctpServerChanneOverUDP.java    From red5-io with Apache License 2.0 6 votes vote down vote up
@Override
public SctpChannel accept() throws IOException, SctpException, InvalidKeyException, NoSuchAlgorithmException {
    logger.setLevel(Level.INFO);

    DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
    SctpPacket packet = null;
    while (true) {
        serverSocket.receive(receivePacket);
        try {
            packet = new SctpPacket(buffer, 0, receivePacket.getLength());
        } catch (SctpException e) {
            logger.log(Level.WARNING, e.getMessage());
            continue;
        }

        logger.log(Level.INFO, "receive new packet");

        InetSocketAddress address = new InetSocketAddress(receivePacket.getAddress(), receivePacket.getPort());
        packet.apply(address, this);

        Association association = pendingAssociations.get(address);
        if (association != null && association.getState() == State.ESTABLISHED) {
            return new SctpChannel(association);
        }
    }
}
 
Example 6
Source File: DatagramProcessorImpl.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
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 7
Source File: IpNetwork.java    From BACnet4J with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Runnable that handles incoming messages
 */
@Override
public void run() {
	byte[] buffer = new byte[MESSAGE_LENGTH];
	final DatagramPacket p = new DatagramPacket(buffer, buffer.length);
	while (!socket.isClosed()) {
		try {
			socket.receive(p);
			final ByteQueue queue = new ByteQueue(p.getData(), 0, p.getLength());
			final OctetString link = new OctetString(p.getAddress().getAddress(), 
					p.getPort());
			IncomingRequestProcessor.getIncomingRequestProcessor().submit(
			new IncomingMessageExecutor(IpNetwork.this, queue, link));
			p.setData(buffer);
		}
		catch (IOException e) {
			// no op. This happens if the socket gets closed by the destroy method.
		}
	}
}
 
Example 8
Source File: DatagramProcessorImpl.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
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: UDPConnManager.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
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 10
Source File: UdpServer.java    From t-io with Apache License 2.0 5 votes vote down vote up
private void startListen() {
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			String startLog = "started tio udp server: " + udpServerConf.getServerNode();
			if (log.isInfoEnabled()) {
				log.info(startLog);
			} else {
				System.out.println(startLog);
			}

			while (!isStopped) {
				try {
					DatagramPacket datagramPacket = new DatagramPacket(readBuf, readBuf.length);
					datagramSocket.receive(datagramPacket);

					byte[] data = new byte[datagramPacket.getLength()];
					System.arraycopy(readBuf, 0, data, 0, datagramPacket.getLength());

					String remoteip = datagramPacket.getAddress().getHostAddress();
					int remoteport = datagramPacket.getPort();
					Node remote = new Node(remoteip, remoteport);
					UdpPacket udpPacket = new UdpPacket(data, remote);

					handlerQueue.put(udpPacket);
				} catch (Throwable e) {
					log.error(e.toString(), e);
				}
			}
		}
	};

	Thread thread = new Thread(runnable, "tio-udp-server-listen");
	thread.setDaemon(false);
	thread.start();
}
 
Example 11
Source File: UDPClient.java    From javacore with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception { // 所有异常抛出
    byte[] buf = new byte[1024]; // 开辟空间,以接收数据
    DatagramSocket ds = new DatagramSocket(9000); // 客户端在9000端口上等待服务器发送信息
    DatagramPacket dp = new DatagramPacket(buf, 1024); // 所有的信息使用buf保存
    ds.receive(dp); // 接收数据
    String str = new String(dp.getData(), 0, dp.getLength()) + "from " + dp.getAddress().getHostAddress() + ":"
        + dp.getPort();
    System.out.println(str); // 输出内容
}
 
Example 12
Source File: VDatagramSocket.java    From finalspeed with GNU General Public License v2.0 5 votes vote down vote up
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 13
Source File: VDatagramSocket.java    From NSS with Apache License 2.0 5 votes vote down vote up
public void send(DatagramPacket p) throws IOException  {
	TCPTun tun=null;
	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 14
Source File: UdpStreamReceiver.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
public void receive() throws InterruptedException, IOException {
    final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    final DataOutputStream dataOut = new DataOutputStream(byteOut);

	isRunning.set(true);
	int packetsReceived = 0;
	
	while(isRunning.get()) {
    	if (Thread.interrupted()) {
    		settings.socket.close();
    		isRunning.set(false);
            throw new InterruptedException();	
           }
		
	    byte data[] = new byte[1024];
	    DatagramPacket packet = new DatagramPacket(data, data.length);
	    
	    settings.socket.receive(packet);
	    packetsReceived++;
	    
	    if (callback != null) {
	    	callback.onReceive(packet);
	    }
	    
	    if (packetsReceived >= settings.packets) {
			isRunning.set(false);
		}
	    
		if (settings.sendResponse) 
		{
			byteOut.reset();

			if (callback != null && callback.onSend(dataOut, packetsReceived)) {
				final byte[] dataToSend = byteOut.toByteArray();
				DatagramPacket dp = new DatagramPacket(dataToSend, dataToSend.length, packet.getAddress(), packet.getPort());
				settings.socket.send(dp);
			}
		}
	}
}
 
Example 15
Source File: VDatagramSocket.java    From finalspeed-91yun with GNU General Public License v2.0 5 votes vote down vote up
public void send(DatagramPacket p) throws IOException  {
	TCPTun tun=null;
	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 16
Source File: DNSTunnel.java    From java-tcp-tunnel with MIT License 4 votes vote down vote up
private String toStr(DatagramPacket packet) {
  String host = packet.getAddress().getHostAddress();
  int port = packet.getPort();
  return host + ":" + port;
}
 
Example 17
Source File: UDPTunnel.java    From java-tcp-tunnel with MIT License 4 votes vote down vote up
private String toStr(DatagramPacket packet) {
  String host = packet.getAddress().getHostAddress();
  int port = packet.getPort();
  return host + ":" + port;
}
 
Example 18
Source File: Socks5DatagramSocket.java    From T0rlib4Android with Apache License 2.0 4 votes vote down vote up
/**
 * Receives udp packet. If packet have arrived from the proxy relay server,
 * it is processed and address and port of the packet are set to the address
 * and port of sending host.<BR>
 * If the packet arrived from anywhere else it is not changed.<br>
 * <B> NOTE: </B> DatagramPacket size should be at least 10 bytes bigger
 * than the largest packet you expect (this is for IPV4 addresses). For
 * hostnames and IPV6 it is even more.
 * 
 * @param dp
 *            Datagram in which all relevent information will be copied.
 */
public void receive(DatagramPacket dp) throws IOException {
	super.receive(dp);

	if (server_mode) {
		// Drop all datagrams not from relayIP/relayPort
		final int init_length = dp.getLength();
		final int initTimeout = getSoTimeout();
		final long startTime = System.currentTimeMillis();

		while (!relayIP.equals(dp.getAddress())
				|| (relayPort != dp.getPort())) {

			// Restore datagram size
			dp.setLength(init_length);

			// If there is a non-infinit timeout on this socket
			// Make sure that it happens no matter how often unexpected
			// packets arrive.
			if (initTimeout != 0) {
				final long passed = System.currentTimeMillis() - startTime;
				final int newTimeout = initTimeout - (int) passed;

				if (newTimeout <= 0) {
					throw new InterruptedIOException(
							"In Socks5DatagramSocket->receive()");
				}
				setSoTimeout(newTimeout);
			}

			super.receive(dp);
		}

		// Restore timeout settings
		if (initTimeout != 0) {
			setSoTimeout(initTimeout);
		}

	} else if (!relayIP.equals(dp.getAddress())
			|| (relayPort != dp.getPort())) {
		return; // Recieved direct packet
		// If the datagram is not from the relay server, return it it as is.
	}

	byte[] data;
	data = dp.getData();

	if (encapsulation != null) {
		data = encapsulation.udpEncapsulate(data, false);
	}

	// FIXME: What is this?
	final int offset = 0; // Java 1.1
	// int offset = dp.getOffset(); //Java 1.2

	final ByteArrayInputStream bIn = new ByteArrayInputStream(data, offset,
			dp.getLength());

	final ProxyMessage msg = new Socks5Message(bIn);
	dp.setPort(msg.port);
	dp.setAddress(msg.getInetAddress());

	// what wasn't read by the Message is the data
	final int data_length = bIn.available();
	// Shift data to the left
	System.arraycopy(data, offset + dp.getLength() - data_length, data,
			offset, data_length);

	dp.setLength(data_length);
}
 
Example 19
Source File: Socks5DatagramSocket.java    From T0rlib4j with Apache License 2.0 4 votes vote down vote up
/**
 * Receives udp packet. If packet have arrived from the proxy relay server,
 * it is processed and address and port of the packet are set to the address
 * and port of sending host.<BR>
 * If the packet arrived from anywhere else it is not changed.<br>
 * <B> NOTE: </B> DatagramPacket size should be at least 10 bytes bigger
 * than the largest packet you expect (this is for IPV4 addresses). For
 * hostnames and IPV6 it is even more.
 * 
 * @param dp
 *            Datagram in which all relevent information will be copied.
 */
public void receive(DatagramPacket dp) throws IOException {
	super.receive(dp);

	if (server_mode) {
		// Drop all datagrams not from relayIP/relayPort
		final int init_length = dp.getLength();
		final int initTimeout = getSoTimeout();
		final long startTime = System.currentTimeMillis();

		while (!relayIP.equals(dp.getAddress())
				|| (relayPort != dp.getPort())) {

			// Restore datagram size
			dp.setLength(init_length);

			// If there is a non-infinit timeout on this socket
			// Make sure that it happens no matter how often unexpected
			// packets arrive.
			if (initTimeout != 0) {
				final long passed = System.currentTimeMillis() - startTime;
				final int newTimeout = initTimeout - (int) passed;

				if (newTimeout <= 0) {
					throw new InterruptedIOException(
							"In Socks5DatagramSocket->receive()");
				}
				setSoTimeout(newTimeout);
			}

			super.receive(dp);
		}

		// Restore timeout settings
		if (initTimeout != 0) {
			setSoTimeout(initTimeout);
		}

	} else if (!relayIP.equals(dp.getAddress())
			|| (relayPort != dp.getPort())) {
		return; // Recieved direct packet
		// If the datagram is not from the relay server, return it it as is.
	}

	byte[] data;
	data = dp.getData();

	if (encapsulation != null) {
		data = encapsulation.udpEncapsulate(data, false);
	}

	// FIXME: What is this?
	final int offset = 0; // Java 1.1
	// int offset = dp.getOffset(); //Java 1.2

	final ByteArrayInputStream bIn = new ByteArrayInputStream(data, offset,
			dp.getLength());

	final ProxyMessage msg = new Socks5Message(bIn);
	dp.setPort(msg.port);
	dp.setAddress(msg.getInetAddress());

	// what wasn't read by the Message is the data
	final int data_length = bIn.available();
	// Shift data to the left
	System.arraycopy(data, offset + dp.getLength() - data_length, data,
			offset, data_length);

	dp.setLength(data_length);
}
 
Example 20
Source File: SnmpResponseHandler.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
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);
            }
        }
    }