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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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: DecompiledMinecraft   File: RConThreadQuery.java   View source code 6 votes vote down vote up
/**
 * Initializes the query system by binding it to a port
 */
private boolean initQuerySystem()
{
    try
    {
        this.querySocket = new DatagramSocket(this.queryPort, InetAddress.getByName(this.serverHostname));
        this.registerSocket(this.querySocket);
        this.querySocket.setSoTimeout(500);
        return true;
    }
    catch (SocketException socketexception)
    {
        this.logWarning("Unable to initialise query system on " + this.serverHostname + ":" + this.queryPort + " (Socket): " + socketexception.getMessage());
    }
    catch (UnknownHostException unknownhostexception)
    {
        this.logWarning("Unable to initialise query system on " + this.serverHostname + ":" + this.queryPort + " (Unknown Host): " + unknownhostexception.getMessage());
    }
    catch (Exception exception)
    {
        this.logWarning("Unable to initialise query system on " + this.serverHostname + ":" + this.queryPort + " (E): " + exception.getMessage());
    }

    return false;
}
 
Example 18
Project: FinalSpeed   File: CapEnv.java   View source code 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 19
Project: gnirehtet   File: Forwarder.java   View source code 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 20
Project: LivroJavaComoProgramar10Edicao   File: Server.java   View source code 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 21
Project: LanChatLite   File: Utils.java   View source code 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 22
Project: cordova-plugin-smartconfig   File: UDPSocketServer.java   View source code 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 23
Project: OpenJSharp   File: SnmpRequestHandler.java   View source code 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 24
Project: myqq   File: UDP.java   View source code 6 votes vote down vote up
/**
 * 获取可用的端口号
 */
public void getMyUsefulPort()
{
	while(true)
	{
   		try
   		{
   			// 实例化一个DatagramSocket
   			socket = new DatagramSocket(myPort);
   			break;
   		}
   		catch (SocketException e)
   		{
   			myPort++;
   		}
	}
}
 
Example 25
Project: Reer   File: FileLockCommunicator.java   View source code 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 26
Project: hadoop   File: RpcProgramNfs3.java   View source code 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 27
Project: litiengine   File: UdpPacketSender.java   View source code 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 28
Project: n4js   File: HttpServerManagerTest.java   View source code 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 29
Project: gree-remote   File: AsyncCommunicator.java   View source code 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 30
Project: FlashLib   File: UDPCommInterface.java   View source code 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 31
Project: hadoop-oss   File: TestGangliaSink.java   View source code 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 32
Project: hadoop-oss   File: TestGangliaSink.java   View source code 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 33
Project: hadoop-oss   File: TestGangliaSink.java   View source code 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 34
Project: hadoop-oss   File: TestStatsDMetrics.java   View source code 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 35
Project: africastalking-android   File: NetworkUtils.java   View source code 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 36
Project: EasyPeasyVPN   File: MediationConnector.java   View source code 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 37
Project: sonos-remote-things   File: SSDPClient.java   View source code 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 38
Project: sonos-remote-things   File: SSDPClient.java   View source code 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 39
Project: hadoop   File: SimpleUdpClient.java   View source code 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 40
Project: openNaEF   File: SimulatedSnmpClientFactory.java   View source code 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);
        }
    };
}