java.net.DatagramSocket Java Examples

The following examples show how to use java.net.DatagramSocket. 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: Ssdp.java    From physical-web with Apache License 2.0 7 votes vote down vote up
public synchronized boolean start(Integer timeout) throws IOException {
  if (mThread == null) {
    // create a DatagramSocket without binding to any address
    mDatagramSocket = new DatagramSocket(null);
    mDatagramSocket.setReuseAddress(true);
    // bind to any free port
    mDatagramSocket.bind(null);
    if (timeout != null && timeout > 0) {
      mDatagramSocket.setSoTimeout(timeout);
    }
    mThread = new Thread(this);
    mThread.start();
    return true;
  }
  return false;
}
 
Example #2
Source File: PrivilegedNfsGatewayStarter.java    From hadoop with Apache License 2.0 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 #3
Source File: DatagramChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private void assertSocketActionAfterConnect(DatagramSocket s) throws IOException {
    assertEquals(s.getPort(), datagramSocket1Address.getPort());
    try {
        s.connect(datagramSocket2Address);
        fail();
    } catch (IllegalStateException expected) {
    }

    assertTrue(this.channel1.isConnected());
    assertTrue(s.isConnected());
    // not changed
    assertEquals(s.getPort(), datagramSocket1Address.getPort());

    s.disconnect();
    assertFalse(this.channel1.isConnected());
    assertFalse(s.isConnected());

    s.close();
    assertTrue(s.isClosed());
    assertFalse(this.channel1.isOpen());
}
 
Example #4
Source File: DatagramLogger.java    From oodt with Apache License 2.0 6 votes vote down vote up
public static void main(String[] argv) throws Throwable {
	if (argv.length > 0) {
		System.err.println("This program takes NO command line arguments.");
		System.err.println("Set the activity.port property to adjust the port number.");
		System.err.println("Set the activity.storage property to set the Storage class to use.");
		System.exit(1);
	}
	int port = Integer.getInteger("activity.port", VAL);
	String className = System.getProperty("activity.storage");
	if (className == null) {
		System.err.println("No Storage class defined via the `activity.storage' property; exiting...");
		System.exit(1);
	}
	Class storageClass = Class.forName(className);
	storage = (Storage) storageClass.newInstance();
	DatagramSocket socket = new DatagramSocket(port);
	byte[] buf = new byte[INT];
	DatagramPacket packet = new DatagramPacket(buf, buf.length);
	for (;;) {
		socket.receive(packet);
		byte[] received = new byte[packet.getLength()];
		System.arraycopy(packet.getData(), packet.getOffset(), received, 0, packet.getLength());
		new ReceiverThread(received).start();
	} 
}
 
Example #5
Source File: WifiIotPlugin.java    From WiFiFlutter with MIT License 6 votes vote down vote up
public static void closeSilently(Object... xs) {
    /// Note: on Android API levels prior to 19 Socket does not implement Closeable
    for (Object x : xs) {
        if (x != null) {
            try {
                if (x instanceof Closeable) {
                    ((Closeable) x).close();
                } else if (x instanceof Socket) {
                    ((Socket) x).close();
                } else if (x instanceof DatagramSocket) {
                    ((DatagramSocket) x).close();
                } else {
                    throw new RuntimeException("cannot close " + x);
                }
            } catch (Throwable e) {
                // TODO : do something ?
            }
        }
    }
}
 
Example #6
Source File: UDPTimeServer.java    From sockslib with Apache License 2.0 6 votes vote down vote up
public void shutdown() {
  try {
    DatagramSocket clientSocket = new DatagramSocket();
    String shutdownSignal = "shutdown";
    byte[] sendBuffer = shutdownSignal.getBytes();
    DatagramPacket packet =
        new DatagramPacket(sendBuffer, sendBuffer.length, new InetSocketAddress("localhost",
            port));
    clientSocket.send(packet);
  } catch (IOException e) {
    logger.error(e.getMessage(), e);
  }
  stop = true;
  if (thread != null) {
    thread.interrupt();
  }
}
 
Example #7
Source File: SnmpRequestHandler.java    From JDKSourceCode1.8 with MIT 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 #8
Source File: SnmpRequestHandler.java    From jdk8u_jdk with GNU General Public License v2.0 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 #9
Source File: RTPSessionMgr.java    From mts with GNU General Public License v3.0 6 votes vote down vote up
private synchronized RTCPReporter startParticipating(DatagramSocket datagramsocket)
throws IOException
{
    UDPPacketSender udppacketsender = new UDPPacketSender(datagramsocket);
    udpPacketSender = udppacketsender;
    if(ttl != 1)
    {
        udppacketsender.setttl(ttl);
    }
    
    // SRIT add for RTP
    RTPRawSender rtprawsender = new RTPRawSender(remoteAddress.getDataPort(), remoteAddress.getControlAddress().getHostName(), udppacketsender);       
    rtpTransmitter = new RTPTransmitter(cache, rtprawsender);
    // rtpTransmitter.setSSRCInfo(cache.ourssrc);
    // RTCPReporter rtpreporter = new RTCPReporter(cache, rtcpTransmitter);

    RTCPRawSender rtcprawsender = new RTCPRawSender(remoteAddress.getControlPort(), remoteAddress.getControlAddress().getHostName(), udppacketsender);
    rtcpTransmitter = new RTCPTransmitter(cache, rtcprawsender);
    rtcpTransmitter.setSSRCInfo(cache.ourssrc);
    RTCPReporter rtcpreporter = new RTCPReporter(cache, rtcpTransmitter);
    
    startedparticipating = true;
    return rtcpreporter;
}
 
Example #10
Source File: NodeDiscovery.java    From db with GNU Affero General Public License v3.0 6 votes vote down vote up
@PostConstruct
private void init() {
    
    if (!configBean.contains(ConfigProperties.CLUSTER_BROADCAST_IP)) {
        logger.warn("Broadcast IP not configured for node. Clustering will be disabled until an appropriate broadcast IP address is set.");
        return;
    }

    beaconListener = new BeaconListener(this);
    beaconListener.start();

    try {
        host = InetAddress.getByName(configBean.getStringProperty(ConfigProperties.CLUSTER_BROADCAST_IP));
        socket = new DatagramSocket();
        byte[] buff = configBean.getStringProperty(ConfigProperties.NODE_ID).getBytes();
        packet = new DatagramPacket(buff, buff.length, host, ClusterConstants.BEACON_PORT);
        broadcastBeacon = true;
        broadcastBeaconAlreadyLogged = false;
    } catch (UnknownHostException | SocketException ex) {
        logger.error("Unable to start node discovery", ex);
    }
}
 
Example #11
Source File: SnmpRequestHandler.java    From jdk8u-jdk with GNU General Public License v2.0 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 #12
Source File: GreeDevice.java    From openhab-greeair-binding with Apache License 2.0 6 votes vote down vote up
public void SetDevicePwrSaving(DatagramSocket clientSocket, Integer value) throws Exception {
    // Only allow this to happen if this device has been bound
    if (getIsBound() != Boolean.TRUE) {
        return;
    }

    // Set the values in the HashMap
    HashMap<String, Integer> parameters = new HashMap<>();
    parameters.put("SvSt", value);
    parameters.put("WdSpd", new Integer(0));
    parameters.put("Quiet", new Integer(0));
    parameters.put("Tur", new Integer(0));
    parameters.put("SwhSlp", new Integer(0));
    parameters.put("SlpMod", new Integer(0));

    ExecuteCommand(clientSocket, parameters);
}
 
Example #13
Source File: PrivateDNS.java    From PacketProxy with Apache License 2.0 6 votes vote down vote up
public PrivateDNSImp(DNSSpoofingIPGetter dnsSpoofingIPGetter) throws Exception {
	try {
		this.spoofingIp = dnsSpoofingIPGetter;
		soc = new DatagramSocket(PORT);
		recvPacket = new DatagramPacket(buf, BUFSIZE);
		sendPacket = null;
	} catch (BindException e) {
		util.packetProxyLogErr("cannot boot private DNS server (permission issue or already listened)");
		return;
	}

	s_sAddr = InetAddress.getByName(dnsServer);
	s_soc = new DatagramSocket();
	s_recvPacket = new DatagramPacket(buf, BUFSIZE);
	s_sendPacket = null;
}
 
Example #14
Source File: UdpConnectThread.java    From FimiX8-RE with MIT License 6 votes vote down vote up
public void run() {
    super.run();
    while (!this.isExit) {
        try {
            if (!SessionManager.getInstance().hasSession()) {
                try {
                    UdpConnect udpConnect = new UdpConnect(new DatagramSocket(), this.option, new DataChanel());
                    udpConnect.startSession();
                    SessionManager.getInstance().addSession(udpConnect);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        } catch (SocketException e2) {
            e2.printStackTrace();
        }
    }
}
 
Example #15
Source File: Socks5UDPAssociateClient.java    From sockslib with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {

    DatagramSocket clientSocket = null;
    Socks5 proxy = new Socks5(new InetSocketAddress("localhost", 1080));

    try {
      NetworkMonitor networkMonitor = new NetworkMonitor();
      clientSocket = new Socks5DatagramSocket(proxy);
      clientSocket = new MonitorDatagramSocketWrapper(clientSocket, networkMonitor);
      String message = "I am client using SOCKS proxy";
      byte[] sendBuffer = message.getBytes();
      DatagramPacket packet =
          new DatagramPacket(sendBuffer, sendBuffer.length, new InetSocketAddress("localhost",
              5050));
      clientSocket.send(packet);


      //Received response message from UDP server.
      byte[] receiveBuf = new byte[100];
      DatagramPacket receivedPacket = new DatagramPacket(receiveBuf, receiveBuf.length);
      clientSocket.receive(receivedPacket);
      String receiveStr = new String(receivedPacket.getData(), 0, receivedPacket.getLength());
      System.out.println("received:" + receiveStr);

      System.out.println("UDP client information:");
      System.out.println("Total Sent:     " + networkMonitor.getTotalSend() + " bytes");
      System.out.println("Total Received: " + networkMonitor.getTotalReceive() + " bytes");
      System.out.println("Total:          " + networkMonitor.getTotal() + " bytes");

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      ResourceUtil.close(clientSocket);
    }

  }
 
Example #16
Source File: RpcProgram.java    From hadoop with Apache License 2.0 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 #17
Source File: InetPortProvider.java    From HolandaCatalinaFw with Apache License 2.0 5 votes vote down vote up
private static boolean probeUdpPort(Integer port) {
    boolean result = true;

    try(DatagramSocket datagramSocket = new DatagramSocket(port)) {
    } catch (Exception ex) {
        result = false;
    }

    return  result;
}
 
Example #18
Source File: JGroupMembershipManager.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void releaseQuorumChecker(QuorumChecker checker) {
  ((QuorumCheckerImpl)checker).teardown();
  InternalDistributedSystem system = InternalDistributedSystem.getAnyInstance();
  if (system == null || !system.isConnected()) {
    DatagramSocket sock = (DatagramSocket)checker.getMembershipInfo();
    if (sock != null  &&  !sock.isClosed()) {
      sock.close();
    }
  }
}
 
Example #19
Source File: DefaultDatagramChannelConfig.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance.
 */
public DefaultDatagramChannelConfig(DatagramChannel channel, DatagramSocket javaSocket) {
    super(channel, new FixedRecvByteBufAllocator(2048));
    if (javaSocket == null) {
        throw new NullPointerException("javaSocket");
    }
    this.javaSocket = javaSocket;
}
 
Example #20
Source File: KadServer.java    From Kademlia with MIT License 5 votes vote down vote up
/**
 * Initialize our KadServer
 *
 * @param udpPort      The port to listen on
 * @param mFactory     Factory used to create messages
 * @param localNode    Local node on which this server runs on
 * @param config
 * @param statistician A statistician to manage the server statistics
 *
 * @throws java.net.SocketException
 */
public KadServer(int udpPort, KademliaMessageFactory mFactory, Node localNode, KadConfiguration config, KadStatistician statistician) throws SocketException
{
    this.config = config;
    this.socket = new DatagramSocket(udpPort);
    this.localNode = localNode;
    this.messageFactory = mFactory;
    this.statistician = statistician;

    /* Start listening for incoming requests in a new thread */
    this.startListener();
}
 
Example #21
Source File: NioUDPDataSender.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private DatagramChannel createChannel(String host, int port, int timeout, int sendBufferSize) {
    DatagramChannel datagramChannel = null;
    DatagramSocket socket = null;
    try {
        datagramChannel = DatagramChannel.open();
        socket = datagramChannel.socket();
        socket.setSoTimeout(timeout);
        socket.setSendBufferSize(sendBufferSize);

        if (logger.isWarnEnabled()) {
            final int checkSendBufferSize = socket.getSendBufferSize();
            if (sendBufferSize != checkSendBufferSize) {
                logger.warn("DatagramChannel.setSendBufferSize() error. {}!={}", sendBufferSize, checkSendBufferSize);
            }
        }

        InetSocketAddress serverAddress = new InetSocketAddress(host, port);
        datagramChannel.connect(serverAddress);

        return datagramChannel;
    } catch (IOException e) {
        IOUtils.closeQuietly(socket);
        IOUtils.closeQuietly(datagramChannel);

        throw new IllegalStateException("DatagramChannel create fail. Cause" + e.getMessage(), e);
    }
}
 
Example #22
Source File: TransportFactory.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
/**
 * Returns new UDP Transport instance
 * connected to specified socket address
 *
 * @param addr
 * @return connected Transport
 * @throws IOException
 */
public static Transport UDPInstance(SocketAddress addr) throws IOException {
    DatagramSocket sock = new DatagramSocket();
    sock.setSoTimeout(getTimeout());
    sock.connect(addr);

    StreamTransport trans = new StreamTransport();
    trans.setStreams(new UDPInputStream(sock), new UDPOutputStream(sock));
    trans.setAddressLabel(addr.toString());
    return trans;
}
 
Example #23
Source File: BroadcastDiscoveryClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private void broadcastToDefaultInterface(DatagramSocket broadcastSocket) {
    try {
        DatagramPacket sendPacket = new DatagramPacket(new byte[0],
                                                       0,
                                                       InetAddress.getByName("255.255.255.255"),
                                                       port);
        broadcastSocket.send(sendPacket);
    } catch (Exception e) {
        logger.warn("Could not broadcast to default interface", e);
    }
}
 
Example #24
Source File: LanServerBroadcastThread.java    From settlers-remake with MIT License 5 votes vote down vote up
private void broadcast(int udpPort, DatagramSocket socket, byte[] data) throws IOException {
	for (NetworkInterface iface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
		for (InetAddress address : Collections.list(iface.getInetAddresses())) {
			if (!address.isSiteLocalAddress())
				continue;
			// Java 1.5 doesn't support getting the subnet mask, so try the two most common.
			byte[] ip = address.getAddress();
			ip[3] = -1; // 255.255.255.0
			socket.send(new DatagramPacket(data, data.length, InetAddress.getByAddress(ip), udpPort));
			ip[2] = -1; // 255.255.0.0
			socket.send(new DatagramPacket(data, data.length, InetAddress.getByAddress(ip), udpPort));
		}
	}
}
 
Example #25
Source File: UdpMultiClientServer.java    From open-rmbt with Apache License 2.0 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 #26
Source File: UDPTestServer.java    From java-tcp-tunnel with MIT License 5 votes vote down vote up
public void runrun() throws Exception {
  DatagramSocket server = new DatagramSocket(port);
  DatagramPacket pkt = new DatagramPacket(receiveBuffer, receiveBuffer.length);
  System.out.println("UDP test server listening on port "+port);
  started = true; //still could race but rather small chance and its just for testing
  server.receive(pkt);
  bytesReceived = pkt.getLength();
  System.out.println("UDP test server received "+bytesReceived+" bytes, exiting.");
  server.close();
}
 
Example #27
Source File: BindFailTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    DatagramSocket s = new DatagramSocket();
    int port = s.getLocalPort();

    for (int i=0; i<32000; i++) {
        try {
            DatagramSocket s2 = new DatagramSocket(port);
        } catch (BindException e) {
        }
    }
}
 
Example #28
Source File: AsyncCommunicator.java    From gree-remote with GNU General Public License v3.0 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
Source File: BadKdc.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static KDC on(int p) throws Exception {
    KDC k = new KDC(OneKDC.REALM, OneKDC.KDCHOST, p, true);
    k.addPrincipal(OneKDC.USER, OneKDC.PASS);
    k.addPrincipalRandKey("krbtgt/" + OneKDC.REALM);
    // Feed a packet to newly started KDC to warm it up
    System.err.println("-------- IGNORE THIS ERROR MESSAGE --------");
    new DatagramSocket().send(
            new DatagramPacket("Hello".getBytes(), 5,
                    InetAddress.getByName(OneKDC.KDCHOST), p));
    return k;
}
 
Example #30
Source File: BindFailTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    DatagramSocket s = new DatagramSocket();
    int port = s.getLocalPort();

    for (int i=0; i<32000; i++) {
        try {
            DatagramSocket s2 = new DatagramSocket(port);
        } catch (BindException e) {
        }
    }
}