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

The following examples show how to use java.net.DatagramPacket#setSocketAddress() . 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: DatagramSocketAdaptor.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void receive(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());
                SocketAddress sender = receive(bb);
                p.setSocketAddress(sender);
                p.setLength(bb.position() - p.getOffset());
            }
        } catch (IOException x) {
            Net.translateException(x);
        }
    }
}
 
Example 2
Source File: DatagramSocketAdaptor.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void receive(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());
                SocketAddress sender = receive(bb);
                p.setSocketAddress(sender);
                p.setLength(bb.position() - p.getOffset());
            }
        } catch (IOException x) {
            Net.translateException(x);
        }
    }
}
 
Example 3
Source File: DatagramSocketAdaptor.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Override
public void receive(DatagramPacket p) throws IOException {
    // get temporary direct buffer with a capacity of p.bufLength
    int bufLength = DatagramPackets.getBufLength(p);
    ByteBuffer bb = Util.getTemporaryDirectBuffer(bufLength);
    try {
        long nanos = MILLISECONDS.toNanos(timeout);
        SocketAddress sender = dc.blockingReceive(bb, nanos);
        bb.flip();
        synchronized (p) {
            // copy bytes to the DatagramPacket and set length
            int len = Math.min(bb.limit(), DatagramPackets.getBufLength(p));
            bb.get(p.getData(), p.getOffset(), len);
            DatagramPackets.setLength(p, len);

            // sender address
            p.setSocketAddress(sender);
        }
    } catch (ClosedChannelException e) {
        var exc = new SocketException("Socket closed");
        exc.initCause(e);
        throw exc;
    } finally {
        Util.offerFirstTemporaryDirectBuffer(bb);
    }
}
 
Example 4
Source File: DatagramSocketAdaptor.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public void receive(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());
                SocketAddress sender = receive(bb);
                p.setSocketAddress(sender);
                p.setLength(bb.position() - p.getOffset());
            }
        } catch (IOException x) {
            Net.translateException(x);
        }
    }
}
 
Example 5
Source File: DNSResolver.java    From personaldnsfilter with GNU General Public License v2.0 6 votes vote down vote up
private void processDatagramPackageMode() throws Exception {
	SocketAddress sourceAdr = dataGramRequest.getSocketAddress();

	//we reuse the request data array
	byte[] data = dataGramRequest.getData();
	DatagramPacket response = new DatagramPacket(data, dataGramRequest.getOffset(), data.length - dataGramRequest.getOffset());

	//forward request to DNS and receive response
	DNSCommunicator.getInstance().requestDNS(dataGramRequest, response);

	// patch the response by applying filter			
	DNSResponsePatcher.patchResponse(sourceAdr.toString(), response.getData(), response.getOffset());

	//finally return the response to the request source
	response.setSocketAddress(sourceAdr);
	replySocket.send(response);
}
 
Example 6
Source File: DNSServer.java    From personaldnsfilter with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void resolve(DatagramPacket request, DatagramPacket response) throws IOException {
    for (int i = 0; i<2; i++) { //retry once in case of EOFException (pooled connection was already closed)
        Connection con = Connection.connect(address, timeout, ssl, null, Proxy.NO_PROXY);
        con.setSoTimeout(timeout);
        try {
            DataInputStream in = new DataInputStream(con.getInputStream());
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeShort(request.getLength());
            out.write(request.getData(), request.getOffset(), request.getLength());
            out.flush();
            int size = in.readShort();
            readResponseFromStream(in, size, response);
            response.setSocketAddress(address);
            con.release(true);
            return;
        } catch (EOFException eof) {
            con.release(false);
            if (i == 1)
                throw new IOException ("EOF when reading from "+this.toString(),eof); // retried already once, now throw exception
        } catch (IOException eio) {
            con.release(false);
            throw eio;
        }
    }
}
 
Example 7
Source File: DatagramSocketAdaptor.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public void receive(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());
                SocketAddress sender = receive(bb);
                p.setSocketAddress(sender);
                p.setLength(bb.position() - p.getOffset());
            }
        } catch (IOException x) {
            Net.translateException(x);
        }
    }
}
 
Example 8
Source File: DNSServer.java    From personaldnsfilter with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void resolve(DatagramPacket request, DatagramPacket response) throws IOException {

    byte[] reqHeader = buildRequestHeader(request.getLength());

    for (int i = 0; i<2; i++) { //retry once in case of EOFException (pooled connection was already closed)
        Connection con = Connection.connect(urlHostAddress, timeout, true, null, Proxy.NO_PROXY);
        try {
            OutputStream out = con.getOutputStream();
            DataInputStream in = new DataInputStream(con.getInputStream());
            out.write(reqHeader);
            out.write(request.getData(), request.getOffset(), request.getLength());
            out.flush();
            HttpHeader responseHeader = new HttpHeader(in, HttpHeader.RESPONSE_HEADER);
            if (responseHeader.getResponseCode() != 200)
                throw new IOException("DoH failed for " + url + "! " + responseHeader.getResponseCode() + " - " + responseHeader.getResponseMessage());

            int size = (int) responseHeader.getContentLength();
            readResponseFromStream(in, size, response);
            response.setSocketAddress(address);
            con.release(true);
            return;
        } catch (EOFException eof) {
            con.release(false);
            if (i == 1)
                throw new IOException ("EOF when reading from "+this.toString(),eof); // retried already once, now throw exception
        } catch (IOException eio) {
            con.release(false);
            throw eio;
        }
    }
}
 
Example 9
Source File: Sender.java    From ict with Apache License 2.0 5 votes vote down vote up
private void sendTransactionToNeighbor(Neighbor nb, Transaction transaction) {
    try {
        DatagramPacket packet = transaction.toDatagramPacket(transactionsToRequest.isEmpty() ? Trytes.NULL_HASH : transactionsToRequest.poll());
        packet.setSocketAddress(nb.getSocketAddress());
        node.socket.send(packet);
    } catch (Exception e) {
        if (isRunning())
            logger.error("Failed to send transaction to neighbor.", e);
    }
}
 
Example 10
Source File: TestOther.java    From ProjectStudy with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    /**
     * 准备发送端
     * DatagramSocket()
     * 构造一个数据报套接字绑定到本地主机机器上的任何可用的端口。
     */
    DatagramSocket ds = new DatagramSocket();
    /**
     * 准备数据包
     *1、 DatagramPacket(byte[] buf, int length)
     * 构造一个 DatagramPacket length接收数据包的长度
     *2、 String的getBytes()
     * 方法是得到一个操作系统默认的编码格式的字节数组
     *3、 setSocketAddress()
     * 设置SocketAddress(通常是IP地址+端口号)都的远程主机发送数据报。
     * 4、InetSocketAddress(InetAddress addr, int port)
     * 创建一个套接字地址的IP地址和端口号。
     */
    String str = "3,19900000001,20171101155915,1,113.26171805987126,23.239234619127426,0.0,192,82|83,WS001,2020051100011002,13570577458";
    byte[] ch = str.getBytes();
    DatagramPacket dp = new DatagramPacket(ch, ch.length);
    dp.setSocketAddress(new InetSocketAddress("127.0.0.1", 4567));
    // 发送数据
    ds.send(dp);
    // 关闭套接字
    ds.close();
}
 
Example 11
Source File: DnsProxy.java    From shadowsocks-android-java with Apache License 2.0 5 votes vote down vote up
public void onDnsRequestReceived(IPHeader ipHeader, UDPHeader udpHeader, DnsPacket dnsPacket) {
    if (!interceptDns(ipHeader, udpHeader, dnsPacket)) {
        //转发DNS
        QueryState state = new QueryState();
        state.ClientQueryID = dnsPacket.Header.ID;
        state.QueryNanoTime = System.nanoTime();
        state.ClientIP = ipHeader.getSourceIP();
        state.ClientPort = udpHeader.getSourcePort();
        state.RemoteIP = ipHeader.getDestinationIP();
        state.RemotePort = udpHeader.getDestinationPort();

        // 转换QueryID
        m_QueryID++;// 增加ID
        dnsPacket.Header.setID(m_QueryID);

        synchronized (m_QueryArray) {
            clearExpiredQueries();//清空过期的查询,减少内存开销。
            m_QueryArray.put(m_QueryID, state);// 关联数据
        }

        InetSocketAddress remoteAddress = new InetSocketAddress(CommonMethods.ipIntToInet4Address(state.RemoteIP), state.RemotePort);
        DatagramPacket packet = new DatagramPacket(udpHeader.m_Data, udpHeader.m_Offset + 8, dnsPacket.Size);
        packet.setSocketAddress(remoteAddress);

        try {
            if (LocalVpnService.Instance.protect(m_Client)) {
                m_Client.send(packet);
            } else {
                System.err.println("VPN protect udp socket failed.");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
 
Example 12
Source File: SyslogSourceTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
protected void sendUdp(String syslog) throws Exception {
	waitUdp();
	DatagramSocket socket = new DatagramSocket();
	DatagramPacket packet = new DatagramPacket(syslog.getBytes(), syslog.length());
	packet.setSocketAddress(new InetSocketAddress("localhost", this.port));
	socket.send(packet);
	socket.close();
}
 
Example 13
Source File: DnsProxy.java    From SmartZPN with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void onDnsRequestReceived(IPHeader ipHeader, UDPHeader udpHeader, DnsPacket dnsPacket) {
    if (!interceptDns(ipHeader, udpHeader, dnsPacket)) {
        //转发DNS
        QueryState state = new QueryState();
        state.ClientQueryID = dnsPacket.Header.ID;
        state.QueryNanoTime = System.nanoTime();
        state.ClientIP = ipHeader.getSourceIP();
        state.ClientPort = udpHeader.getSourcePort();
        state.RemoteIP = ipHeader.getDestinationIP();
        state.RemotePort = udpHeader.getDestinationPort();

        // 转换QueryID
        mQueryID++;// 增加ID
        dnsPacket.Header.setID(mQueryID);

        synchronized (mQueryArray) {
            clearExpiredQueries();//清空过期的查询,减少内存开销。
            mQueryArray.put(mQueryID, state);// 关联数据
        }

        InetSocketAddress remoteAddress = new InetSocketAddress(ProxyUtils.ipIntToInet4Address(state.RemoteIP), state.RemotePort);
        DatagramPacket packet = new DatagramPacket(udpHeader.m_Data, udpHeader.m_Offset + 8, dnsPacket.Size);
        packet.setSocketAddress(remoteAddress);

        try {
            if (LocalVpnService.Instance.protect(mClient)) {
                mClient.send(packet);
            } else {
                System.err.println("VPN protect udp socket failed.");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
 
Example 14
Source File: DnsProxy.java    From SmartProxy with GNU General Public License v3.0 5 votes vote down vote up
public void onDnsRequestReceived(IPHeader ipHeader,UDPHeader udpHeader,DnsPacket dnsPacket){
	if(!interceptDns(ipHeader,udpHeader,dnsPacket)){
	    //ת��DNS
		QueryState state = new QueryState();
		state.ClientQueryID =dnsPacket.Header.ID;
		state.QueryNanoTime = System.nanoTime();
		state.ClientIP = ipHeader.getSourceIP();
		state.ClientPort = udpHeader.getSourcePort();
		state.RemoteIP = ipHeader.getDestinationIP();
		state.RemotePort = udpHeader.getDestinationPort();

		// ת��QueryID
		m_QueryID++;// ����ID
		dnsPacket.Header.setID(m_QueryID);
		
		synchronized (m_QueryArray) {
			clearExpiredQueries();//��չ��ڵIJ�ѯ�������ڴ濪����
			m_QueryArray.put(m_QueryID, state);// ��������
		}
		
		InetSocketAddress remoteAddress = new InetSocketAddress(CommonMethods.ipIntToInet4Address(state.RemoteIP ), state.RemotePort);
		DatagramPacket packet = new DatagramPacket(udpHeader.m_Data, udpHeader.m_Offset+8, dnsPacket.Size);
		packet.setSocketAddress(remoteAddress);

		try {
			if(LocalVpnService.Instance.protect(m_Client)){
				m_Client.send(packet);
			}else {
				System.err.println("VPN protect udp socket failed.");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
 
Example 15
Source File: KadServer.java    From Kademlia with MIT License 5 votes vote down vote up
/**
 * Internal sendMessage method called by the public sendMessage method after a communicationId is generated
 */
private void sendMessage(Node to, Message msg, int comm) throws IOException
{
    /* Use a try-with resource to auto-close streams after usage */
    try (ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout);)
    {
        /* Setup the message for transmission */
        dout.writeInt(comm);
        dout.writeByte(msg.code());
        msg.toStream(dout);
        dout.close();

        byte[] data = bout.toByteArray();

        if (data.length > DATAGRAM_BUFFER_SIZE)
        {
            throw new IOException("Message is too big");
        }

        /* Everything is good, now create the packet and send it */
        DatagramPacket pkt = new DatagramPacket(data, 0, data.length);
        pkt.setSocketAddress(to.getSocketAddress());
        socket.send(pkt);

        /* Lets inform the statistician that we've sent some data */
        this.statistician.sentData(data.length);
    }
}
 
Example 16
Source File: SocketManagerTest.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
/**
   * @param args
   */
  public static void main(String[] args) throws Exception {
  	
      host = Utils.getLocalAddress().getHostAddress();
      port = 10000;
  	transport = "udp";

  	InetSocketAddress localDatagramSocketAddress = new InetSocketAddress(host, port);
  	DatagramSocket datagramSocket = new DatagramSocket(localDatagramSocketAddress);
  	
  	String packet = createRequest(0);
  	byte[] data = Utils.parseBinaryString(packet);
      System.out.println("length = " + data.length);

DatagramPacket dp = new DatagramPacket(data, data.length);
      InetSocketAddress remoteDatagramSocketAddress = new InetSocketAddress(host, port);
      dp.setSocketAddress(remoteDatagramSocketAddress);

      int maxIter = 100000;
      System.out.println("maxIter : " + maxIter);
      
      long beginTT = new GregorianCalendar().getTimeInMillis();
      for (int i = 1; i <= maxIter; i++) {
          // Create a message object corresponding to the string message
          if (i % 1000 == 0) {
              // System.out.println("i=" + i);
          }
          
          // MsgUdp msg = new MsgUdp(data, data.length);
          // msg.setListenpoint(listenpoint);
          
  		dp.setData(data);
          // remoteDatagramSocketAddress = new InetSocketAddress(host, port);
          dp.setSocketAddress(remoteDatagramSocketAddress);
  		
	datagramSocket.send(dp);            
      }
      long endTT = new GregorianCalendar().getTimeInMillis();
      float duration = ((float)(endTT - beginTT)) / 1000;
      float flow = maxIter / duration;
      System.out.println("nombre trans = " + maxIter + " msg.");
      System.out.println("duration = " + duration + " s.");
      System.out.println("msg flow = " + flow + " msg/s.");

      System.out.println("Hit enter to terminate server");
      System.in.read();

  }
 
Example 17
Source File: DHTTrackerPluginAlt.java    From BiglyBT with GNU General Public License v2.0 4 votes vote down vote up
private byte[]
send(
	GetPeersTask		task,
	DatagramSocket		server,
	InetSocketAddress	address,
	Map<String,Object>	map )

	throws IOException
{
	byte[]	tid;

	while( true ){

		tid = new byte[4];

		RandomUtils.nextBytes( tid );

		synchronized( tid_map ){

			if ( tid_map.containsKey( tid )){

				continue;
			}

			tid_map.put( tid, new Object[]{ task, SystemTime.getMonotonousTime() });

			if ( timer_event == null ){

				timer_event =
					SimpleTimer.addPeriodicEvent(
						"dhtalttimer",
						2500,
						new TimerEventPerformer()
						{
							@Override
							public void
							perform(
								TimerEvent event)
							{
								checkTimeouts();

								synchronized( tid_map ){

									if ( tid_map.size() == 0 ){

										timer_event.cancel();

										timer_event = null;
									}
								}
							}
						});
			}
		}

		try{
			map.put( "t", tid );

			// System.out.println( "Sending: " + map );

			byte[] 	data_out = BEncoder.encode( map );

			DatagramPacket packet = new DatagramPacket( data_out, data_out.length);

			packet.setSocketAddress( address );

			packets_out++;
			bytes_out += data_out.length;

			server.send( packet );

			return( tid );

		}catch( Throwable e ){

			try{
				server.close();

			}catch( Throwable f ){

			}

			synchronized( tid_map ){

				tid_map.remove( tid );
			}

			if ( e instanceof IOException ){

				throw((IOException)e);

			}else{

				throw(new IOException(Debug.getNestedExceptionMessage(e)));
			}
		}
	}
}
 
Example 18
Source File: DHTTrackerPluginAlt.java    From TorrentEngine with GNU General Public License v3.0 2 votes vote down vote up
private byte[]
send(
	GetPeersTask		task,
	DatagramSocket		server,
	InetSocketAddress	address,
	Map<String,Object>	map )
	
	throws IOException
{
	byte[]	tid;
	
	while( true ){
		
		tid = new byte[4];
		
		RandomUtils.nextBytes( tid );

		synchronized( tid_map ){
			
			if ( tid_map.containsKey( tid )){
				
				continue;
			}
			
			tid_map.put( tid, new Object[]{ task, SystemTime.getMonotonousTime() });
			
			if ( timer_event == null ){
				
				timer_event = 
					SimpleTimer.addPeriodicEvent(
						"dhtalttimer",
						2500,
						new TimerEventPerformer() 
						{	
							public void 
							perform(
								TimerEvent event) 
							{
								checkTimeouts();
								
								synchronized( tid_map ){
									
									if ( tid_map.size() == 0 ){
										
										timer_event.cancel();
										
										timer_event = null;
									}
								}
							}
						});
			}
		}
		
		try{
			map.put( "t", tid );
	
			// System.out.println( "Sending: " + map );
				
			byte[] 	data_out = BEncoder.encode( map );
			
			DatagramPacket packet = new DatagramPacket( data_out, data_out.length);
			
			packet.setSocketAddress( address );
	
			packets_out++;
			bytes_out += data_out.length;
					
			server.send( packet );
			
			return( tid );
			
		}catch( Throwable e ){
			
			try{
				server.close();
				
			}catch( Throwable f ){
				
			}
			
			synchronized( tid_map ){

				tid_map.remove( tid );
			}
			
			if ( e instanceof IOException ){
				
				throw((IOException)e);
				
			}else{
				
				throw(new IOException(Debug.getNestedExceptionMessage(e)));
			}
		}
	}
}