Java Code Examples for java.net.datagramsocket#getLocalAddress()

The following examples show how to use java.net.datagramsocket#getLocalAddress() . 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: UpnpSettingsResource.java    From ha-bridge with Apache License 2.0 6 votes vote down vote up
private InetAddress getOutboundAddress(String remoteAddress, int remotePort) {
	InetAddress localAddress = null;
	try {
	DatagramSocket sock = new DatagramSocket();
	// connect is needed to bind the socket and retrieve the local address
	// later (it would return 0.0.0.0 otherwise)
	sock.connect(new InetSocketAddress(remoteAddress, remotePort));
	localAddress = sock.getLocalAddress();
	sock.disconnect();
	sock.close();
	sock = null;
	} catch(Exception e)  {
		ParseRoute theRoute = ParseRoute.getInstance();
		try {
			localAddress = InetAddress.getByName(theRoute.getLocalIPAddress());
		} catch(Exception e1) {}
		log.warn("Error <" + e.getMessage() + "> on determining interface to reply for <" + remoteAddress + ">. Using default route IP Address of " + localAddress.getHostAddress());
	}
	log.debug("getOutbountAddress returning IP Address of " + localAddress.getHostAddress());
	return localAddress;
}
 
Example 2
Source File: ImageTransmitter.java    From Smack with Apache License 2.0 6 votes vote down vote up
public ImageTransmitter(DatagramSocket socket, InetAddress remoteHost, int remotePort, Rectangle area) {

        try {
            robot = new Robot();

            maxI = (int) Math.ceil(area.getWidth() / tileWidth);
            maxJ = (int) Math.ceil(area.getHeight() / tileWidth);

            tiles = new int[maxI][maxJ][tileWidth * tileWidth];

            this.area = area;
            this.socket = socket;
            localHost = socket.getLocalAddress();
            localPort = socket.getLocalPort();
            this.remoteHost = remoteHost;
            this.remotePort = remotePort;
            this.encoder = new DefaultEncoder();

            transmit = true;

        }
        catch (AWTException e) {
            LOGGER.log(Level.WARNING, "exception", e);
        }

    }
 
Example 3
Source File: ReuseAddressTest.java    From openjdk-jdk9 with GNU General Public License v2.0 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 4
Source File: NetUtil.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Get the ip address of local host.
 */
public static String getHostAddress()
    throws SocketException, UnknownHostException {
  DatagramSocket ds = new DatagramSocket();
  ds.connect(InetAddress.getByName(DUMMY_OUT_IP), 80);
  InetAddress localAddress = ds.getLocalAddress();
  if (localAddress.getHostAddress().equals("0.0.0.0")) {
    localAddress = InetAddress.getLocalHost();
  }
  return localAddress.getHostAddress();
}
 
Example 5
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 6
Source File: DiscoveryTest.java    From freeacs with MIT License 4 votes vote down vote up
private boolean test2()
    throws UtilityException, SocketException, UnknownHostException, IOException,
        MessageAttributeParsingException, MessageAttributeException,
        MessageHeaderParsingException {
  int timeSinceFirstTransmission = 0;
  int timeout = timeoutInitValue;
  do {
    try {
      // Test 2 including response
      DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0));
      sendSocket.connect(InetAddress.getByName(stunServer), port);
      sendSocket.setSoTimeout(timeout);

      MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
      sendMH.generateTransactionID();

      ChangeRequest changeRequest = new ChangeRequest();
      changeRequest.setChangeIP();
      changeRequest.setChangePort();
      sendMH.addMessageAttribute(changeRequest);

      byte[] data = sendMH.getBytes();
      DatagramPacket send = new DatagramPacket(data, data.length);
      sendSocket.send(send);
      LOGGER.debug("Test 2: Binding Request sent.");

      int localPort = sendSocket.getLocalPort();
      InetAddress localAddress = sendSocket.getLocalAddress();

      sendSocket.close();

      DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress);
      receiveSocket.connect(ca.getAddress().getInetAddress(), ca.getPort());
      receiveSocket.setSoTimeout(timeout);

      MessageHeader receiveMH = new MessageHeader();
      while (!receiveMH.equalTransactionID(sendMH)) {
        DatagramPacket receive = new DatagramPacket(new byte[200], 200);
        receiveSocket.receive(receive);
        receiveMH = MessageHeader.parseHeader(receive.getData());
        receiveMH.parseAttributes(receive.getData());
      }
      ErrorCode ec =
          (ErrorCode)
              receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
      if (ec != null) {
        di.setError(ec.getResponseCode(), ec.getReason());
        LOGGER.debug("Message header contains an Errorcode message attribute.");
        return false;
      }
      if (!nodeNatted) {
        di.setOpenAccess();
        LOGGER.debug(
            "Node has open access to the Internet (or, at least the node is behind a full-cone NAT without translation).");
      } else {
        di.setFullCone();
        LOGGER.debug("Node is behind a full-cone NAT.");
      }
      return false;
    } catch (SocketTimeoutException ste) {
      if (timeSinceFirstTransmission < 7900) {
        LOGGER.debug("Test 2: Socket timeout while receiving the response.");
        timeSinceFirstTransmission += timeout;
        int timeoutAddValue = timeSinceFirstTransmission * 2;
        if (timeoutAddValue > 1600) {
          timeoutAddValue = 1600;
        }
        timeout = timeoutAddValue;
      } else {
        LOGGER.debug(
            "Test 2: Socket timeout while receiving the response. Maximum retry limit exceed. Give up.");
        if (!nodeNatted) {
          di.setSymmetricUDPFirewall();
          LOGGER.debug("Node is behind a symmetric UDP firewall.");
          return false;
        } else {
          // not is natted
          // redo test 1 with address and port as offered in the changed-address message attribute
          return true;
        }
      }
    }
  } while (true);
}
 
Example 7
Source File: DiscoveryTest.java    From freeacs with MIT License 4 votes vote down vote up
private void test3()
    throws UtilityException, SocketException, UnknownHostException, IOException,
        MessageAttributeParsingException, MessageAttributeException,
        MessageHeaderParsingException {
  int timeSinceFirstTransmission = 0;
  int timeout = timeoutInitValue;
  do {
    try {
      // Test 3 including response
      DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0));
      sendSocket.connect(InetAddress.getByName(stunServer), port);
      sendSocket.setSoTimeout(timeout);

      MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
      sendMH.generateTransactionID();

      ChangeRequest changeRequest = new ChangeRequest();
      changeRequest.setChangePort();
      sendMH.addMessageAttribute(changeRequest);

      byte[] data = sendMH.getBytes();
      DatagramPacket send = new DatagramPacket(data, data.length);
      sendSocket.send(send);
      LOGGER.debug("Test 3: Binding Request sent.");

      int localPort = sendSocket.getLocalPort();
      InetAddress localAddress = sendSocket.getLocalAddress();

      sendSocket.close();

      DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress);
      receiveSocket.connect(InetAddress.getByName(stunServer), ca.getPort());
      receiveSocket.setSoTimeout(timeout);

      MessageHeader receiveMH = new MessageHeader();
      while (!receiveMH.equalTransactionID(sendMH)) {
        DatagramPacket receive = new DatagramPacket(new byte[200], 200);
        receiveSocket.receive(receive);
        receiveMH = MessageHeader.parseHeader(receive.getData());
        receiveMH.parseAttributes(receive.getData());
      }
      ErrorCode ec =
          (ErrorCode)
              receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
      if (ec != null) {
        di.setError(ec.getResponseCode(), ec.getReason());
        LOGGER.debug("Message header contains an Errorcode message attribute.");
        return;
      }
      if (nodeNatted) {
        di.setRestrictedCone();
        LOGGER.debug("Node is behind a restricted NAT.");
        return;
      }
    } catch (SocketTimeoutException ste) {
      if (timeSinceFirstTransmission < 7900) {
        LOGGER.debug("Test 3: Socket timeout while receiving the response.");
        timeSinceFirstTransmission += timeout;
        int timeoutAddValue = timeSinceFirstTransmission * 2;
        if (timeoutAddValue > 1600) {
          timeoutAddValue = 1600;
        }
        timeout = timeoutAddValue;
      } else {
        LOGGER.debug(
            "Test 3: Socket timeout while receiving the response. Maximum retry limit exceed. Give up.");
        di.setPortRestrictedCone();
        LOGGER.debug("Node is behind a port restricted NAT.");
        return;
      }
    }
  } while (true);
}