Java Code Examples for java.net.DatagramSocket

The following are top voted examples for showing how to use java.net.DatagramSocket. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: OCast-Java   File: SSDPDiscoveryTest.java   Source Code and License 6 votes vote down vote up
@Test
public void scanSingleResult() throws Exception {
    final DatagramSocket socketMessage = mock(DatagramSocket.class);
    doAnswer(new ReceiveAnswer(new String[]{GOOD_SSDP_PAYLOAD1})).when(socketMessage).receive(any(DatagramPacket.class));

    FakeExecutorListener callback = Mockito.spy(new FakeExecutorListener());
    SSDPDiscovery ssdp = new SSDPDiscovery("urn:cast-ocast-org:service:cast:1", 3000) {
        @Override
        protected DatagramSocket createSocket() {
            return socketMessage;
        }
    };
    ssdp.addListener(callback);
    ssdp.start();
    callback.await(3, TimeUnit.SECONDS);
    verify(callback, times(1)).onLocationSent();
    verify(callback, times(1)).onLocationReceived(any(SSDPMessage.class));
    SSDPMessage result = callback.getResult();
    assertThat(result.getUuid(), is(equalTo("c4323fee-db4b-4227-9039-fa4b71589e26")));
}
 
Example 2
Project: jdk8u-jdk   File: SnmpRequestHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Full constructor
 */
public SnmpRequestHandler(SnmpAdaptorServer server, int id,
                          DatagramSocket s, DatagramPacket p,
                          SnmpMibTree tree, Vector<SnmpMibAgent> m,
                          InetAddressAcl a,
                          SnmpPduFactory factory,
                          SnmpUserDataFactory dataFactory,
                          MBeanServer f, ObjectName n)
{
    super(server, id, f, n);

    // Need a reference on SnmpAdaptorServer for getNext & getBulk,
    // in case of oid equality (mib overlapping).
    //
    adaptor = server;
    socket = s;
    packet = p;
    root= tree;
    mibs = new Vector<>(m);
    subs= new Hashtable<>(mibs.size());
    ipacl = a;
    pduFactory = factory ;
    userDataFactory = dataFactory ;
    //thread.start();
}
 
Example 3
Project: OCast-Java   File: SSDPDiscoveryTest.java   Source Code and License 6 votes vote down vote up
@Override
public DatagramSocket answer(InvocationOnMock invocation) throws Throwable {
    //if needed, the Socket can be retrieved with:
    //DatagramSocket socket = (DatagramSocket) invocation.getMock();
    int timeout = 5000;
    Object[] args = invocation.getArguments();
    if (mCount < mResponseToSend) {
        Thread.sleep(timeout/2);
        ((DatagramPacket) args[0]).setData(mAnswers[mCount].getBytes());
        mCount++;
        return null;
    } else {
        Thread.sleep(timeout);
        throw new InterruptedIOException();
    }
}
 
Example 4
Project: scorekeeperfrontend   File: Network.java   Source Code and License 6 votes vote down vote up
/**
 * For multihomed machines (i.e. anything with Docker Machine), use the 
 * routing table default route to find what should be the primary network
 * facing interface.
 * @return an InetAddress for the primary address
 */
public static InetAddress getPrimaryAddress()
{
    InetAddress ret;
    try {
        DatagramSocket s = new DatagramSocket();
        s.connect(InetAddress.getByAddress(new byte[]{1,1,1,1}), 0);
        ret = s.getLocalAddress();
        s.close();
        return ret;
    } catch (SocketException | UnknownHostException se) {
        log.info("get by route failed: " + se);
    } 
    
    try {
        return InetAddress.getLocalHost();
    } catch (UnknownHostException ex) {
        log.info("getLocalHost failed: " + ex);
    }
 
    return InetAddress.getLoopbackAddress();
}
 
Example 5
Project: OCast-Java   File: SSDPDiscoveryTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testScanWithWrongST() throws Exception {
    final DatagramSocket socketMessage = mock(DatagramSocket.class);
    doAnswer(new ReceiveAnswer(new String[]{GOOD_SSDP_PAYLOAD1})).when(socketMessage).receive(Mockito.any(DatagramPacket.class));

    FakeExecutorListener callback = Mockito.spy(new FakeExecutorListener());
    SSDPDiscovery ssdp = new SSDPDiscovery("urn:dummy:service:vucast:1", 3000) {
        @Override
        protected DatagramSocket createSocket() {
            return socketMessage;
        }
    };
    ssdp.addListener(callback);
    ssdp.start();
    callback.await(3, TimeUnit.SECONDS);
    verify(callback, times(1)).onLocationSent();
    verify(callback, times(0)).onLocationReceived(any(SSDPMessage.class));
}
 
Example 6
Project: ipack   File: UDPTransport.java   Source Code and License 6 votes vote down vote up
public UDPTransport(DatagramSocket socket, int mtu)
    throws IOException
{

    if (!socket.isBound() || !socket.isConnected())
    {
        throw new IllegalArgumentException("'socket' must be bound and connected");
    }

    this.socket = socket;

    // NOTE: As of JDK 1.6, can use NetworkInterface.getMTU

    this.receiveLimit = mtu - MIN_IP_OVERHEAD - UDP_OVERHEAD;
    this.sendLimit = mtu - MAX_IP_OVERHEAD - UDP_OVERHEAD;
}
 
Example 7
Project: Transmission   File: BroadcastDiscover.java   Source Code and License 6 votes vote down vote up
private void receiveBroadcast(DatagramSocket datagramSocket) throws IOException {
        byte[] data = new byte[2048];
        while (receive) {
            DatagramPacket datagramPacket = new DatagramPacket(data, data.length);
            datagramSocket.receive(datagramPacket);
            DataResult data1 = UnPacket.getInstance().getData(datagramPacket.getData());
            if (data1 != null && data1.isResult() && data1.getT().getDataType()==Packet.DATA_TYPE_ONLINE) {
//                data1.getType()
//                TLog.e(data1.toString());
                if (listener != null) {
                    listener.receiver(data1);
                }
            }

//        String s =  new String(datagramPacket.getData());
////        TLog.e("address : " + datagramPacket.getAddress() + ", port : " + datagramPacket.getPort() + ", content : " + s);
//            if (listener!=null){
//                listener.receiver(s);
//            }
        }
    }
 
Example 8
Project: Sem-Update   File: VentanaPrincipal.java   Source Code and License 6 votes vote down vote up
private void jButtonDetenerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDetenerActionPerformed
    try {
        // Se intenta conectar, retorna IOException en caso que no pueda
        DatagramSocket clienteSocket = new DatagramSocket();
        byte[] bufferOut = new byte[1000];
        
        String mensajeAMandar = "Mata server" + id;
        bufferOut = mensajeAMandar.getBytes();
        IPServer = InetAddress.getByName(servidor);

        DatagramPacket sendPacket = new DatagramPacket(bufferOut, bufferOut.length, IPServer, numeroPuerto);
        clienteSocket.send(sendPacket);

        jLabel1.setForeground(Color.red);
        clienteSocket.close();
        url.setText("");
        jlabelSQL.setText("");
        this.setTitle("App [ID:?]");
    } catch (IOException ex) {
        System.out.println("(LOG) [ERROR] No se pudo contactar al servidor");
        Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 9
Project: boohee_v5.6   File: Network.java   Source Code and License 6 votes vote down vote up
public static String getIp() {
    IOException e;
    try {
        DatagramSocket socket = new DatagramSocket();
        try {
            socket.connect(InetAddress.getByName("114.114.114.114"), 53);
            InetAddress local = socket.getLocalAddress();
            socket.close();
            return local.getHostAddress();
        } catch (IOException e2) {
            e = e2;
            DatagramSocket datagramSocket = socket;
            e.printStackTrace();
            return "";
        }
    } catch (IOException e3) {
        e = e3;
        e.printStackTrace();
        return "";
    }
}
 
Example 10
Project: broadlink-java-api   File: BLDevice.java   Source Code and License 6 votes vote down vote up
/**
 * Constructs a <code>BLDevice</code>, with a device type (constants),
 * hostname and MAC address
 * 
 * @param deviceType
 *            Device type constants (<code>BLDevice.DEV_*</code>)
 * @param devDesc
 *            Friendly device description
 * @param host
 *            Hostname of target Broadlink device
 * @param mac
 *            MAC address of target Broadlink device
 * @throws IOException
 *             Problems on constructing a datagram socket
 */
protected BLDevice(short deviceType, String deviceDesc, String host, Mac mac) throws IOException {
    key = INITIAL_KEY;
    iv = INITIAL_IV;
    id = new byte[] { 0, 0, 0, 0 };

    pktCount = new Random().nextInt(0xffff);
    // pktCount = 0;

    this.deviceType = deviceType;
    this.deviceDesc = deviceDesc;
    
    this.host = host;
    this.mac = mac;

    sock = new DatagramSocket(0);
    sock.setReuseAddress(true);
    sock.setBroadcast(true);
}
 
Example 11
Project: fuck_zookeeper   File: LENonTerminateTest.java   Source Code and License 6 votes vote down vote up
/**
 * MockServer plays the role of peer C. Respond to two requests for votes
 * with vote for self and then Assert.fail. 
 */
void mockServer() throws InterruptedException, IOException {          
    byte b[] = new byte[36];
    ByteBuffer responseBuffer = ByteBuffer.wrap(b);
    DatagramPacket packet = new DatagramPacket(b, b.length);
    QuorumServer server = peers.get(Long.valueOf(2));
    DatagramSocket udpSocket = new DatagramSocket(server.addr.getPort());
    LOG.info("In MockServer");
    mockLatch.countDown();
    Vote current = new Vote(2, 1);
    for (int i=0;i<2;++i) {
        udpSocket.receive(packet);
        responseBuffer.rewind();
        LOG.info("Received " + responseBuffer.getInt() + " " + responseBuffer.getLong() + " " + responseBuffer.getLong());
        LOG.info("From " + packet.getSocketAddress());
        responseBuffer.clear();
        responseBuffer.getInt(); // Skip the xid
        responseBuffer.putLong(2);
        
        responseBuffer.putLong(current.getId());
        responseBuffer.putLong(current.getZxid());
        packet.setData(b);
        udpSocket.send(packet);
    }
}
 
Example 12
Project: java-coap   File: DatagramSocketTransportTest.java   Source Code and License 6 votes vote down vote up
@Test
public void sendingCoapWithTrafficClass() throws Exception {
    final DatagramSocket socket = spy(new QoSDatagramSocket(new InetSocketAddress(0)));
    DatagramSocketTransport trans = spy(createDatagramSocketTransport());
    when(trans.createSocket()).thenReturn(socket);

    CoapClient client = CoapClientBuilder.newBuilder(5683).transport(trans).timeout(10000).build();

    client.resource("/test").context(TrafficClassTransportContext.create(TrafficClassTransportContext.HIGH, TransportContext.NULL)).get();
    verify(socket).setTrafficClass(TrafficClassTransportContext.HIGH);
    verify(socket).setTrafficClass(0);

    reset(socket);
    client.resource("/test").get();
    verify(socket, never()).setTrafficClass(anyInt());

    client.close();
}
 
Example 13
Project: https-github.com-apache-zookeeper   File: AuthFastLeaderElection.java   Source Code and License 6 votes vote down vote up
private void starter(QuorumPeer self) {
    this.self = self;
    port = self.getVotingView().get(self.getId()).electionAddr.getPort();
    proposedLeader = -1;
    proposedZxid = -1;

    try {
        mySocket = new DatagramSocket(port);
        // mySocket.setSoTimeout(20000);
    } catch (SocketException e1) {
        e1.printStackTrace();
        throw new RuntimeException();
    }
    sendqueue = new LinkedBlockingQueue<ToSend>(2 * self.getVotingView().size());
    recvqueue = new LinkedBlockingQueue<Notification>(2 * self.getVotingView()
            .size());
    new Messenger(self.getVotingView().size() * 2, mySocket);
}
 
Example 14
Project: BiglyBT   File: DHTTrackerPluginAlt.java   Source Code and License 6 votes vote down vote up
private
GetPeersTask(
	DatagramSocket								_server,
	List<DHTTransportAlternativeContact>		_contacts,
	byte[]										_torrent_hash,
	boolean										_no_seeds,
	LookupListener								_listener )
{
	server			= _server;
	torrent_hash	= _torrent_hash;
	no_seeds		= _no_seeds;
	listener		= _listener;

	initial_contacts = _contacts;

	tryQuery();
}
 
Example 15
Project: hadoop   File: PrivilegedNfsGatewayStarter.java   Source Code and License 6 votes vote down vote up
@Override
public void init(DaemonContext context) throws Exception {
  System.err.println("Initializing privileged NFS client socket...");
  NfsConfiguration conf = new NfsConfiguration();
  int clientPort = conf.getInt(NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY,
      NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_DEFAULT);
  if (clientPort < 1 || clientPort > 1023) {
    throw new RuntimeException("Must start privileged NFS server with '" +
        NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY + "' configured to a " +
        "privileged port.");
  }
  registrationSocket = new DatagramSocket(
      new InetSocketAddress("localhost", clientPort));
  registrationSocket.setReuseAddress(true);
  args = context.getArguments();
}
 
Example 16
Project: ZooKeeper   File: LENonTerminateTest.java   Source Code and License 6 votes vote down vote up
/**
 * MockServer plays the role of peer C. Respond to two requests for votes
 * with vote for self and then Assert.fail. 
 */
void mockServer() throws InterruptedException, IOException {          
    byte b[] = new byte[36];
    ByteBuffer responseBuffer = ByteBuffer.wrap(b);
    DatagramPacket packet = new DatagramPacket(b, b.length);
    QuorumServer server = peers.get(Long.valueOf(2));
    DatagramSocket udpSocket = new DatagramSocket(server.addr.getPort());
    LOG.info("In MockServer");
    mockLatch.countDown();
    Vote current = new Vote(2, 1);
    for (int i=0;i<2;++i) {
        udpSocket.receive(packet);
        responseBuffer.rewind();
        LOG.info("Received " + responseBuffer.getInt() + " " + responseBuffer.getLong() + " " + responseBuffer.getLong());
        LOG.info("From " + packet.getSocketAddress());
        responseBuffer.clear();
        responseBuffer.getInt(); // Skip the xid
        responseBuffer.putLong(2);
        
        responseBuffer.putLong(current.getId());
        responseBuffer.putLong(current.getZxid());
        packet.setData(b);
        udpSocket.send(packet);
    }
}
 
Example 17
Project: FinalSpeed   File: CapEnv.java   Source Code and License 6 votes vote down vote up
private void detectMac_udp(){
	for(int i=0;i<10;i++){
		try {
			DatagramSocket ds=new DatagramSocket();
			DatagramPacket dp=new DatagramPacket(new byte[1000], 1000);
			dp.setAddress(InetAddress.getByName(testIp_udp));
			dp.setPort(5555);
			ds.send(dp);
			ds.close();
			Thread.sleep(500);
			if(local_mac!=null){
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				Thread.sleep(1);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}

}
 
Example 18
Project: gnirehtet   File: Forwarder.java   Source Code and License 6 votes vote down vote up
/**
 * Neither vpnInterface.close() nor vpnInputStream.close() wake up a blocking
 * vpnInputStream.read().
 * <p>
 * Therefore, we need to make Android send a packet to the VPN interface (here by sending a UDP
 * packet), so that any blocking read will be woken up.
 * <p>
 * Since the tunnel is closed at this point, it will never reach the network.
 */
private void wakeUpReadWorkaround() {
    // network actions may not be called from the main thread
    EXECUTOR_SERVICE.execute(new Runnable() {
        @Override
        public void run() {
            try {
                DatagramSocket socket = new DatagramSocket();
                InetAddress dummyAddr = InetAddress.getByAddress(DUMMY_ADDRESS);
                DatagramPacket packet = new DatagramPacket(new byte[0], 0, dummyAddr, DUMMY_PORT);
                socket.send(packet);
            } catch (IOException e) {
                // ignore
            }
        }
    });
}
 
Example 19
Project: LivroJavaComoProgramar10Edicao   File: Server.java   Source Code and License 6 votes vote down vote up
public Server()
{
   super("Server");

   displayArea = new JTextArea(); // create displayArea
   add(new JScrollPane(displayArea), BorderLayout.CENTER);
   setSize(400, 300); // set size of window
   setVisible(true); // show window

   try // create DatagramSocket for sending and receiving packets
   {
      socket = new DatagramSocket(5000);
   } 
   catch (SocketException socketException) 
   {
      socketException.printStackTrace();
      System.exit(1);
   } 
}
 
Example 20
Project: LanChatLite   File: Utils.java   Source Code and License 6 votes vote down vote up
public static void sendUdpMsg(String msg, String ip, int port) {
  try {

    InetAddress address = InetAddress.getByName(ip);
  	
    // Initialize a datagram packet with data and address
    DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.length(), address, port);

    // Create a datagram socket, send the packet through it, close it.
    DatagramSocket dsocket = new DatagramSocket();
    dsocket.send(packet);
    dsocket.close();
  } catch (Exception e) {
    System.err.println(e);
  }
}
 
Example 21
Project: cordova-plugin-smartconfig   File: UDPSocketServer.java   Source Code and License 6 votes vote down vote up
/**
 * Constructor of UDP Socket Server
 * 
 * @param port
 *            the Socket Server port
 * @param socketTimeout
 *            the socket read timeout
 * @param context
 *            the context of the Application
 */
public UDPSocketServer(int port, int socketTimeout, Context context) {
	this.mContext = context;
	this.buffer = new byte[64];
	this.mReceivePacket = new DatagramPacket(buffer, 64);
	try {
		this.mServerSocket = new DatagramSocket(port);
		this.mServerSocket.setSoTimeout(socketTimeout);
		this.mIsClosed = false;
		WifiManager manager = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		mLock = manager.createMulticastLock("test wifi");
		Log.d(TAG, "mServerSocket is created, socket read timeout: "
				+ socketTimeout + ", port: " + port);
	} catch (IOException e) {
		Log.e(TAG, "IOException");
		e.printStackTrace();
	}
}
 
Example 22
Project: OpenJSharp   File: SnmpRequestHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Full constructor
 */
public SnmpRequestHandler(SnmpAdaptorServer server, int id,
                          DatagramSocket s, DatagramPacket p,
                          SnmpMibTree tree, Vector<SnmpMibAgent> m,
                          InetAddressAcl a,
                          SnmpPduFactory factory,
                          SnmpUserDataFactory dataFactory,
                          MBeanServer f, ObjectName n)
{
    super(server, id, f, n);

    // Need a reference on SnmpAdaptorServer for getNext & getBulk,
    // in case of oid equality (mib overlapping).
    //
    adaptor = server;
    socket = s;
    packet = p;
    root= tree;
    mibs = new Vector<>(m);
    subs= new Hashtable<>(mibs.size());
    ipacl = a;
    pduFactory = factory ;
    userDataFactory = dataFactory ;
    //thread.start();
}
 
Example 23
Project: myqq   File: UDP.java   Source Code and License 6 votes vote down vote up
/**
 * 获取可用的端口号
 */
public void getMyUsefulPort()
{
	while(true)
	{
   		try
   		{
   			// 实例化一个DatagramSocket
   			socket = new DatagramSocket(myPort);
   			break;
   		}
   		catch (SocketException e)
   		{
   			myPort++;
   		}
	}
}
 
Example 24
Project: Reer   File: FileLockCommunicator.java   Source Code and License 5 votes vote down vote up
public FileLockCommunicator(InetAddressFactory addressFactory) {
    this.addressFactory = addressFactory;
    try {
        socket = new DatagramSocket(0, addressFactory.getLocalBindingAddress());
    } catch (SocketException e) {
        throw throwAsUncheckedException(e);
    }
}
 
Example 25
Project: hadoop   File: RpcProgramNfs3.java   Source Code and License 5 votes vote down vote up
public static RpcProgramNfs3 createRpcProgramNfs3(NfsConfiguration config,
    DatagramSocket registrationSocket, boolean allowInsecurePorts)
    throws IOException {
  DefaultMetricsSystem.initialize("Nfs3");
  String displayName = DNS.getDefaultHost("default", "default")
      + config.getInt(NfsConfigKeys.DFS_NFS_SERVER_PORT_KEY,
          NfsConfigKeys.DFS_NFS_SERVER_PORT_DEFAULT);
  metrics = Nfs3Metrics.create(config, displayName);
  return new RpcProgramNfs3(config, registrationSocket, allowInsecurePorts);
}
 
Example 26
Project: litiengine   File: UdpPacketSender.java   Source Code and License 5 votes vote down vote up
/**
 * Instantiates a new udp packet sender.
 */
public UdpPacketSender() {
  try {
    this.socket = new DatagramSocket();
  } catch (final SocketException e) {
    log.log(Level.SEVERE, e.getMessage(), e);
  }
}
 
Example 27
Project: n4js   File: HttpServerManagerTest.java   Source Code and License 5 votes vote down vote up
private boolean isRunning(final int port) {
	if (0 > port || 65535 < port) {
		throw new IllegalArgumentException("Invalid port number: " + port);
	}
	try (final ServerSocket ss = new ServerSocket(port); final DatagramSocket ds = new DatagramSocket(port)) {
		ss.setReuseAddress(true);
		ds.setReuseAddress(true);
		return false;
	} catch (final IOException e) {
		return true;
	}
}
 
Example 28
Project: gree-remote   File: AsyncCommunicator.java   Source Code and License 5 votes vote down vote up
private boolean createSocket() {
    try {
        mSocket = new DatagramSocket(new InetSocketAddress(DATAGRAM_PORT));
    } catch (SocketException e) {
        Log.e(LOG_TAG, "Failed to create socket. Error: " + e.getMessage());
        return false;
    }

    return true;
}
 
Example 29
Project: FlashLib   File: UDPCommInterface.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void setLocalAddress(InetAddress addr) {
	if (isConnected() || !isOpened()) return;
	
	disconnect();
	
	try {
		socket = new DatagramSocket(socket.getLocalPort(), addr);
	} catch (IOException e) {
		e.printStackTrace();
	}
	
}
 
Example 30
Project: hadoop-oss   File: TestGangliaSink.java   Source Code and License 5 votes vote down vote up
@Test
public void testShouldCreateDatagramSocketByDefault() throws Exception {
    SubsetConfiguration conf = new ConfigBuilder()
            .subset("test.sink.ganglia");

    GangliaSink30 gangliaSink = new GangliaSink30();
    gangliaSink.init(conf);
    DatagramSocket socket = gangliaSink.getDatagramSocket();
    assertFalse("Did not create DatagramSocket", socket == null || socket instanceof MulticastSocket);
}
 
Example 31
Project: hadoop-oss   File: TestGangliaSink.java   Source Code and License 5 votes vote down vote up
@Test
public void testShouldCreateDatagramSocketIfMulticastIsDisabled() throws Exception {
    SubsetConfiguration conf = new ConfigBuilder()
            .add("test.sink.ganglia.multicast", false)
            .subset("test.sink.ganglia");
    GangliaSink30 gangliaSink = new GangliaSink30();
    gangliaSink.init(conf);
    DatagramSocket socket = gangliaSink.getDatagramSocket();
    assertFalse("Did not create DatagramSocket", socket == null || socket instanceof MulticastSocket);
}
 
Example 32
Project: hadoop-oss   File: TestGangliaSink.java   Source Code and License 5 votes vote down vote up
@Test
public void testShouldCreateMulticastSocket() throws Exception {
    SubsetConfiguration conf = new ConfigBuilder()
            .add("test.sink.ganglia.multicast", true)
            .subset("test.sink.ganglia");
    GangliaSink30 gangliaSink = new GangliaSink30();
    gangliaSink.init(conf);
    DatagramSocket socket = gangliaSink.getDatagramSocket();
    assertTrue("Did not create MulticastSocket", socket != null && socket instanceof MulticastSocket);
    int ttl = ((MulticastSocket) socket).getTimeToLive();
    assertEquals("Did not set default TTL", 1, ttl);
}
 
Example 33
Project: hadoop-oss   File: TestStatsDMetrics.java   Source Code and License 5 votes vote down vote up
@Test(timeout=3000)
public void testPutMetrics() throws IOException, InterruptedException {
  final StatsDSink sink = new StatsDSink();
  List<MetricsTag> tags = new ArrayList<MetricsTag>();
  tags.add(new MetricsTag(MsInfo.Hostname, "host"));
  tags.add(new MetricsTag(MsInfo.Context, "jvm"));
  tags.add(new MetricsTag(MsInfo.ProcessName, "process"));
  Set<AbstractMetric> metrics = new HashSet<AbstractMetric>();
  metrics.add(makeMetric("foo1", 1.25, MetricType.COUNTER));
  metrics.add(makeMetric("foo2", 2.25, MetricType.GAUGE));
  final MetricsRecord record =
      new MetricsRecordImpl(MsInfo.Context, (long) 10000, tags, metrics);

  try (DatagramSocket sock = new DatagramSocket()) {
    sock.setReceiveBufferSize(8192);
    final StatsDSink.StatsD mockStatsD =
        new StatsD(sock.getLocalAddress().getHostName(),
            sock.getLocalPort());
    Whitebox.setInternalState(sink, "statsd", mockStatsD);
    final DatagramPacket p = new DatagramPacket(new byte[8192], 8192);
    sink.putMetrics(record);
    sock.receive(p);

    String result =new String(p.getData(), 0, p.getLength(),
        Charset.forName("UTF-8"));
    assertTrue(
        "Received data did not match data sent",
        result.equals("host.process.jvm.Context.foo1:1.25|c") ||
        result.equals("host.process.jvm.Context.foo2:2.25|g"));

  } finally {
    sink.close();
  }
}
 
Example 34
Project: africastalking-android   File: NetworkUtils.java   Source Code and License 5 votes vote down vote up
static String determineLocalIp() {
    try {
        DatagramSocket s = new DatagramSocket();
        s.connect(InetAddress.getByName("192.168.1.1"), 80);
        return s.getLocalAddress().getHostAddress();
    } catch (IOException e) {
        Log.e("determineLocalIp()", e.getMessage() + "");
        // dont do anything; there should be a connectivity change going
        return null;
    }
}
 
Example 35
Project: EasyPeasyVPN   File: MediationConnector.java   Source Code and License 5 votes vote down vote up
public String getAccessibleNetworkAddressAtMediator(String networkName, Mediator mediator) {

        // TODO: Remove as soon as mediation is working..
        if (true) {
            return "0:0";
        }

        try {
            DatagramSocket clientSocket = new DatagramSocket();
            byte[] sendData = ("JOIN:" + networkName).getBytes("UTF-8");
            DatagramPacket sendPacket = new DatagramPacket(sendData,
                    sendData.length, InetAddress.getByName(mediator.getUrl()), Constants.MEDIATION_SERVER_PORT);
            clientSocket.send(sendPacket);

            DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 1024);
            clientSocket.receive(receivePacket);
            String response = new String(receivePacket.getData());
            response = NetworkUtilities.getCleanString(response);
            System.out.println("Response: " + response);
            if(response.equals("ERROR"))
                return null;
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
Example 36
Project: sonos-remote-things   File: SSDPClient.java   Source Code and License 5 votes vote down vote up
/**
 * Discover any UPNP device using SSDP (Simple Service Discovery Protocol).
 * @param timeout in milliseconds
 * @param serviceType if null it use "ssdp:all"
 * @return List of devices discovered
 * @throws IOException
 * @see <a href="https://en.wikipedia.org/wiki/Simple_Service_Discovery_Protocol">SSDP Wikipedia Page</a>
 */
public static List<Device> discover(int timeout, String serviceType) throws IOException {
    ArrayList<Device> devices = new ArrayList<Device>();
    byte[] sendData;
    byte[] receiveData = new byte[1024];

    /* Create the search request */
    StringBuilder msearch = new StringBuilder(
            "M-SEARCH * HTTP/1.1\nHost: 239.255.255.250:1900\nMan: \"ssdp:discover\"\n");
    if (serviceType == null) { msearch.append("ST: ssdp:all\n"); }
    else { msearch.append("ST: ").append(serviceType).append("\n"); }

    /* Send the request */
    sendData = msearch.toString().getBytes();
    DatagramPacket sendPacket = new DatagramPacket(
            sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900);
    DatagramSocket clientSocket = new DatagramSocket();
    clientSocket.setSoTimeout(timeout);
    clientSocket.send(sendPacket);

    /* Receive all responses */
    while (true) {
        try {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            clientSocket.receive(receivePacket);
            devices.add(Device.parse(receivePacket));
        }
        catch (SocketTimeoutException e) { break; }
    }

    clientSocket.close();
    return Collections.unmodifiableList(devices);
}
 
Example 37
Project: sonos-remote-things   File: SSDPClient.java   Source Code and License 5 votes vote down vote up
public static Device discoverOne(int timeout, String serviceType) throws IOException {
    Device device = null;
    byte[] sendData;
    byte[] receiveData = new byte[1024];

    /* Create the search request */
    StringBuilder msearch = new StringBuilder(
            "M-SEARCH * HTTP/1.1\nHost: 239.255.255.250:1900\nMan: \"ssdp:discover\"\n");
    if (serviceType == null) { msearch.append("ST: ssdp:all\n"); }
    else { msearch.append("ST: ").append(serviceType).append("\n"); }

    /* Send the request */
    sendData = msearch.toString().getBytes();
    DatagramPacket sendPacket = new DatagramPacket(
            sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900);
    DatagramSocket clientSocket = new DatagramSocket();
    clientSocket.setSoTimeout(timeout);
    clientSocket.send(sendPacket);

    /* Receive one response */
    try {
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        device = Device.parse(receivePacket);
    }
    catch (SocketTimeoutException e) { }

    clientSocket.close();
    return device;
}
 
Example 38
Project: hadoop   File: SimpleUdpClient.java   Source Code and License 5 votes vote down vote up
public void run() throws IOException {
  InetAddress IPAddress = InetAddress.getByName(host);
  byte[] sendData = request.getBytes();
  byte[] receiveData = new byte[65535];
  // Use the provided socket if there is one, else just make a new one.
  DatagramSocket socket = this.clientSocket == null ?
      new DatagramSocket() : this.clientSocket;

  try {
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
        IPAddress, port);
    socket.send(sendPacket);
    socket.setSoTimeout(500);
    DatagramPacket receivePacket = new DatagramPacket(receiveData,
        receiveData.length);
    socket.receive(receivePacket);

    // Check reply status
    XDR xdr = new XDR(Arrays.copyOfRange(receiveData, 0,
        receivePacket.getLength()));
    RpcReply reply = RpcReply.read(xdr);
    if (reply.getState() != RpcReply.ReplyState.MSG_ACCEPTED) {
      throw new IOException("Request failed: " + reply.getState());
    }
  } finally {
    // If the client socket was passed in to this UDP client, it's on the
    // caller of this UDP client to close that socket.
    if (this.clientSocket == null) {
      socket.close();
    }
  }
}
 
Example 39
Project: openNaEF   File: SimulatedSnmpClientFactory.java   Source Code and License 5 votes vote down vote up
public SnmpClient createSnmpClient(
        final InetAddress nodeAddress,
        SimulationEntry entry)
        throws IOException {
    if (nodeAddress == null) {
        throw new IOException("nodeAddress == null");
    }
    if (archive == null) {
        throw new IOException("archive is null");
    }
    if (!archive.exists(nodeAddress.getHostAddress())) {
        throw new IOException("no simulationEntry found: " + nodeAddress.getHostAddress());
    }
    DatagramSocket socket = new DatagramSocket();
    final SnmpAgentEmulator agentEmulator =
            new SnmpAgentEmulator(
                    new ZipFile(archive.getSimulationArchiveFile()),
                    entry.getMibZipEntryName(),
                    socket);
    agentEmulator.start();
    return new SnmpClient(
            InetAddress.getLocalHost(),
            socket.getLocalPort(),
            "public".getBytes(),
            new SnmpClientLogger()) {
        public void close() {
            try {
                agentEmulator.stop();
            } catch (Exception e) {
                log.info(e.toString());
            }
        }

        public InetSocketAddress getSnmpAgentAddress() {
            return new InetSocketAddress(nodeAddress, 0);
        }
    };
}
 
Example 40
Project: tg-qq-trans   File: QQRunner.java   Source Code and License 5 votes vote down vote up
public QQRunner(ConfigData configData)
{
	this.configData = configData;
	try
	{
		ds = new DatagramSocket();
	} catch (SocketException e)
	{
		System.out.println("错误:创建UDP链接对象时出错");
		e.printStackTrace();
	}
	qqPic = new GetQQPic(configData);
	sendMessages = new LinkedList<String>();
	receiveMessages = new LinkedList<String>();
}
 
Example 41
Project: Sem-Update   File: ServidorThread.java   Source Code and License 5 votes vote down vote up
public ServidorThread(DatagramPacket cliente, DatagramSocket servidor) {
    this.clientePacket = cliente;
    this.servidorSocket = servidor;

    shell = Runtime.getRuntime();
    db = new DB();
    db.conectar();
    try {
        System.out.println("(LOG) [OK] Packet cliente [" + clientePacket.getAddress().getHostAddress() + "] capturado");
    } catch (Exception ex) {
        System.out.println("(LOG) [ERROR] No se pudo comunicar con el cliente");
        Logger.getLogger(ServidorThread.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 42
Project: openjdk-jdk10   File: ReuseAddressTest.java   Source Code and License 5 votes vote down vote up
String getInfo(DatagramSocket soc) {
    if (soc == null) {
        return null;
    }

    return "localPort: " + soc.getLocalPort()
            + "; localAddress: " + soc.getLocalAddress()
            + "; remotePort: " + soc.getPort()
            + "; remoteAddress: " + soc.getInetAddress()
            + "; isClosed: " + soc.isClosed()
            + "; isBound: " + soc.isBound();
}
 
Example 43
Project: java-open-nl   File: Client.java   Source Code and License 5 votes vote down vote up
private static void initializeClientSocket(){ 
	try {
		Client.socket = new DatagramSocket();
	} catch (SocketException e) { 
		System.out.println("Error while initializing client's socket: " + e.getMessage()); 
	}
}
 
Example 44
Project: samba-documents-provider   File: BroadcastBrowsingProvider.java   Source Code and License 5 votes vote down vote up
@Override
public List<String> call() throws Exception {
  try (DatagramSocket socket = new DatagramSocket()) {
    InetAddress address = InetAddress.getByName(mBroadcastAddress);

    sendNameQueryBroadcast(socket, address);

    return listenForServers(socket);
  }
}
 
Example 45
Project: hadoop   File: RpcProgram.java   Source Code and License 5 votes vote down vote up
/**
 * Constructor
 * 
 * @param program program name
 * @param host host where the Rpc server program is started
 * @param port port where the Rpc server program is listening to
 * @param progNumber program number as defined in RFC 1050
 * @param lowProgVersion lowest version of the specification supported
 * @param highProgVersion highest version of the specification supported
 * @param registrationSocket if not null, use this socket to register
 *        with portmap daemon
 * @param allowInsecurePorts true to allow client connections from
 *        unprivileged ports, false otherwise
 */
protected RpcProgram(String program, String host, int port, int progNumber,
    int lowProgVersion, int highProgVersion,
    DatagramSocket registrationSocket, boolean allowInsecurePorts) {
  this.program = program;
  this.host = host;
  this.port = port;
  this.progNumber = progNumber;
  this.lowProgVersion = lowProgVersion;
  this.highProgVersion = highProgVersion;
  this.registrationSocket = registrationSocket;
  this.allowInsecurePorts = allowInsecurePorts;
  LOG.info("Will " + (allowInsecurePorts ? "" : "not ") + "accept client "
      + "connections from unprivileged ports");
}
 
Example 46
Project: javase   File: UDPClient.java   Source Code and License 5 votes vote down vote up
public UDPClient() {
	try {
		datagramSocket = new DatagramSocket();
	} catch (SocketException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 47
Project: RiderUnity3DConnector   File: UnityConnectorServer.java   Source Code and License 5 votes vote down vote up
public boolean startServer() {
    if (serverRunnable != null && serverRunnable.isRunning()) {
        // Server is already running
        return true;
    }
    try {
        datagramSocket = new DatagramSocket(port);
        serverRunnable = new ServerRunnable();
        executorService.execute(serverRunnable);
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 48
Project: hadoop   File: SimpleUdpClient.java   Source Code and License 5 votes vote down vote up
public SimpleUdpClient(String host, int port, XDR request, Boolean oneShot,
    DatagramSocket clientSocket) {
  this.host = host;
  this.port = port;
  this.request = request;
  this.oneShot = oneShot;
  this.clientSocket = clientSocket;
}
 
Example 49
Project: highfrequencyrobots   File: UDPSender.java   Source Code and License 5 votes vote down vote up
@Override
protected void establishConnection(InetAddress addr) {
  try {
    socket = new DatagramSocket(mHostPort);
    mLog.debug("Established local socket at ", mHostPort, " with a destination of ", addr, ":", mDestPort);
    update(mStatus.connectionEstablished());
  } catch (SocketException e) {
    e.printStackTrace();
  }
  startSendThread(addr);
}
 
Example 50
Project: CustomWorldGen   File: ThreadLanServerPing.java   Source Code and License 5 votes vote down vote up
public ThreadLanServerPing(String p_i1321_1_, String p_i1321_2_) throws IOException
{
    super("LanServerPinger #" + UNIQUE_THREAD_ID.incrementAndGet());
    this.motd = p_i1321_1_;
    this.address = p_i1321_2_;
    this.setDaemon(true);
    this.socket = new DatagramSocket();
}
 
Example 51
Project: FlashLib   File: CameraServer.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a new CameraServer. A datagram socket is created and listens for incoming data on a specific port. A data
 * reading and sending thread is created and started immediately. Upon handshake initiation from a client, data from
 * the defined camera is sent by calling the {@link Camera#getData()} method for bytes and sending them using the
 * datagram socket.
 * 
 * @param name for logging data
 * @param localPort port to listen for incoming data
 * @param camera camera whose data is sent
 */
public CameraServer(String name, int localPort, Camera camera){
	port = localPort;
	logName = name+"-CameraServer";
	try {
		socket = new DatagramSocket(new InetSocketAddress(localPort));
	} catch (SocketException e) {
		e.printStackTrace();
	}
	
	this.camera = camera;
	runThread = new Thread(new Task(this));
	runThread.start();
}
 
Example 52
Project: CustomWorldGen   File: RConThreadBase.java   Source Code and License 5 votes vote down vote up
/**
 * Closes all of the opened sockets
 */
protected void closeAllSockets_do(boolean logWarning)
{
    int i = 0;

    for (DatagramSocket datagramsocket : this.socketList)
    {
        if (this.closeSocket(datagramsocket, false))
        {
            ++i;
        }
    }

    this.socketList.clear();

    for (ServerSocket serversocket : this.serverSocketList)
    {
        if (this.closeServerSocket_do(serversocket, false))
        {
            ++i;
        }
    }

    this.serverSocketList.clear();

    if (logWarning && 0 < i)
    {
        this.logWarning("Force closed " + i + " sockets");
    }
}
 
Example 53
Project: open-rmbt   File: UdpSingleClientServer.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @param socket
 * @param timeOut
 * @param token
 * @throws SocketException
 */
public UdpSingleClientServer(DatagramSocket socket, int timeOut, ClientToken token) throws SocketException {
	TestServerConsole.log("Starting UdpSingleClientServer on port: " + socket.getLocalPort(), 0, TestServerServiceEnum.UDP_SERVICE);
	this.socket = socket;
	this.socket.setSoTimeout(timeOut);
	this.isRunning = new AtomicBoolean(false);
	this.token = token;
	this.numPackets = 0;
}
 
Example 54
Project: open-rmbt   File: UdpMultiClientServer.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @param port
 * @param timeOut
 * @throws Exception 
 */
public UdpMultiClientServer(int port, InetAddress address) throws Exception {
	super(DatagramSocket.class);
	TestServerConsole.log("Initializing " + TAG + " on " + address + ":" + port, 1, TestServerServiceEnum.TEST_SERVER);
	//this.socket = new DatagramSocket(port, TestServer.serverPreferences.getInetAddrBindTo());
	this.socket = TestServer.createDatagramSocket(port, address);
	this.port = port;
	this.isRunning = new AtomicBoolean(false);
	this.address = address;
	this.name = "UdpMultiClientServer [" + address + ":" + port + "]";
}
 
Example 55
Project: open-rmbt   File: UdpMultiClientServer.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @param socket
 */
public UdpMultiClientServer(DatagramSocket socket) {
	super(DatagramSocket.class);
	this.socket = socket;
	this.port = socket.getLocalPort();
	this.address = socket.getLocalAddress();
	this.isRunning = new AtomicBoolean(false);
	this.name = "UdpMultiClientServer [" + address + ":" + socket.getLocalPort() + "]";
}
 
Example 56
Project: open-rmbt   File: ClientHandler.java   Source Code and License 5 votes vote down vote up
/**
   * 
   * @param command
   * @param token
   * @throws IOException
   * @throws InterruptedException 
   */
  private void runIncomingUdpTest(final String command, final ClientToken token) throws IOException, InterruptedException {
  	final int port;
  	final int timeout = 5000;
final int numPackets;
  	
Pattern p = Pattern.compile(QoSServiceProtocol.CMD_UDP_TEST_IN + " ([\\d]*) ([\\d]*)");
Matcher m = p.matcher(command);
m.find();
if (m.groupCount()!=2) {
	throw new IOException("udp incoming test command syntax error: " + command);
}
else {
	port = Integer.parseInt(m.group(1));
	numPackets = Integer.parseInt(m.group(2));
}	

//DatagramSocket sock = new DatagramSocket(port);
final UdpTestCandidate clientData = new UdpTestCandidate();
clientData.setNumPackets(numPackets);
final DatagramSocket sock = new DatagramSocket();

final CountDownLatch latch = new CountDownLatch(1);
final Runnable sendUdpPacketsRunnable = new Runnable() {
	
	@Override
	public void run() {
		sendUdpPackets(socket.getInetAddress(), sock, port, 3000, numPackets, true, 100, token, clientData);
		latch.countDown();
	}
};

TestServer.getCommonThreadPool().execute(sendUdpPacketsRunnable);

final Matcher idMatcher = ID_REGEX_PATTERN.matcher(command);
if (!idMatcher.find()) {
	latch.await(timeout, TimeUnit.MILLISECONDS);
	sendRcvResult(clientData, port, command);
}
  }
 
Example 57
Project: jaer   File: SpiNNaker_HardwareInterface.java   Source Code and License 5 votes vote down vote up
/** Constructs a new SpiNNaker_HardwareInterface using the input and output stream supplied. The other arguments should only have one non-null entry and 
 * are used to properly close the interface.
 * @param socket - or supply this (not both)
 */
public SpiNNaker_HardwareInterface(DatagramSocket socket) {
    this.socket = socket;
    if (socket == null) {
        throw new Error( "Cannot create SpiNNaker_HardwareInterface with null socket");
    }
}
 
Example 58
Project: T0rlib4Android   File: UDPRelayServer.java   Source Code and License 5 votes vote down vote up
private void pipe(DatagramSocket from, DatagramSocket to, boolean out)
		throws IOException {
	final byte[] data = new byte[datagramSize];
	final DatagramPacket dp = new DatagramPacket(data, data.length);

	while (true) {
		try {
			from.receive(dp);
			lastReadTime = System.currentTimeMillis();

			if (auth.checkRequest(dp, out)) {
				to.send(dp);
			}

		} catch (final UnknownHostException uhe) {
			log.info("Dropping datagram for unknown host");
		} catch (final InterruptedIOException iioe) {
			// log("Interrupted: "+iioe);
			// If we were interrupted by other thread.
			if (iddleTimeout == 0) {
				return;
			}

			// If last datagram was received, long time ago, return.
			final long timeSinceRead = System.currentTimeMillis()
					- lastReadTime;
			if (timeSinceRead >= iddleTimeout - 100) {
				return;
			}
		}
		dp.setLength(data.length);
	}
}
 
Example 59
Project: CustomWorldGen   File: RConThreadBase.java   Source Code and License 5 votes vote down vote up
/**
 * Closes the specified DatagramSocket
 */
protected boolean closeSocket(DatagramSocket socket, boolean removeFromList)
{
    this.logDebug("closeSocket: " + socket);

    if (null == socket)
    {
        return false;
    }
    else
    {
        boolean flag = false;

        if (!socket.isClosed())
        {
            socket.close();
            flag = true;
        }

        if (removeFromList)
        {
            this.socketList.remove(socket);
        }

        return flag;
    }
}
 
Example 60
Project: broadlink-java-api   File: BLDevice.java   Source Code and License 5 votes vote down vote up
/**
 * Sends a compiled packet to a destination host and port, and receives a
 * datagram from the source port specified.
 * 
 * @param sock
 *            Uses an external socket
 * @param pkt
 *            The compiled packet to be sent
 * @param sourceIpAddr
 *            Source IP address to be binded for receiving datagrams
 * @param sourcePort
 *            Source Port to be bineded for receiving datagrams
 * @param destIpAddr
 *            Destination IP address
 * @param destPort
 *            Destination Port
 * @param timeout
 *            Socket timeout. 0 will disable the timeout
 * @param bufSize
 *            Receiving datagram's buffer size
 * @return The received datagram
 * @throws IOException
 *             Thrown if socket timed out, cannot bind source IP and source
 *             port, no permission, etc.
 */
public static DatagramPacket sendPkt(DatagramSocket sock, Packet pkt, InetAddress sourceIpAddr, int sourcePort,
        InetAddress destIpAddr, int destPort, int timeout, int bufSize) throws IOException {
    // sock.bind(new InetSocketAddress(ipAddr, sourcePort));

    byte[] data = pkt.getData();
    log.debug("DESTIP: " + destIpAddr.getHostAddress());
    log.debug("DESTPORT: " + destPort);
    DatagramPacket sendpack = new DatagramPacket(data, data.length, destIpAddr, destPort);
    sock.send(sendpack);

    byte[] rece = new byte[bufSize];
    DatagramPacket recepack = new DatagramPacket(rece, 0, rece.length);

    long startTime = System.currentTimeMillis();
    long elapsed;
    while ((elapsed = System.currentTimeMillis() - startTime) < timeout) {
        try {
            sock.send(sendpack);
            sock.setSoTimeout(1000);
            sock.receive(recepack);
            break;
        } catch (SocketTimeoutException e) {
            if (elapsed > timeout) {
                break;
            }

            continue;
        }
    }

    return recepack;
}