@Override
  public int send(String mess) throws Exception, RemoteException, RemoteException {
    if (s == null) {
      try {
        group = InetAddress.getByName(config.getGroup());
        if (config.getHost() != null) {
          InetAddress addr = InetAddress.getByName(config.getHost());
          InetSocketAddress addrs = new InetSocketAddress(addr, config.getMultiport());
          s = new MulticastSocket(addrs);
        } else s = new MulticastSocket(config.getMultiport());

        s.setTimeToLive(config.getTtl());
        s.joinGroup(group);
      } catch (Exception ex) {
        log.error("Unable to use multicast: " + ex);
        s = null;
        return -1;
      }
    }

    byte[] buf;
    buf = mess.getBytes(US_ASCII);
    DatagramPacket data = new DatagramPacket(buf, buf.length, group, config.getMultiport());
    try {
      s.send(data);
    } catch (Exception ex) {
      log.error("Unable to send colllected load information: " + ex);
      s.close();
      s = null;
      return -1;
    }
    return 0;
  }
Пример #2
0
  /**
   * Connect the socket. Called by MIOPListener.
   *
   * @param profile
   * @param time_out unused, we use SO_TIMEOUT
   */
  @Override
  public void connect(Profile profile, long time_out) {
    if (!is_connected()) {
      if (profile instanceof MIOPProfile) {
        this.profile = (MIOPProfile) profile;
      } else {
        throw new org.omg.CORBA.BAD_PARAM(
            "attempt to connect an MIOP connection "
                + "to a non-MIOP profile: "
                + profile.getClass());
      }

      try {
        socket = new MulticastSocket(((MIOPProfile) profile).getUIPMCProfile().the_port);

        socket.setSoTimeout(socketTimeout);
        socket.setTimeToLive(timeToLive);
        socket.joinGroup(((MIOPProfile) profile).getGroupInetAddress());

        connection_info = socket.toString();
      } catch (Exception e) {
        if (socket != null) {
          socket.close();
        }
        throw new RuntimeException("Can't create multicast socket: " + profile);
      }

      connected = true;

      groupListener.start();
    }
  }
 private void createSocket() throws IOException {
   if (this.getTheSocket() == null) {
     MulticastSocket socket;
     if (this.isAcknowledge()) {
       if (logger.isDebugEnabled()) {
         logger.debug("Listening for acks on port: " + this.getAckPort());
       }
       if (localAddress == null) {
         socket = new MulticastSocket(this.getAckPort());
       } else {
         InetAddress whichNic = InetAddress.getByName(this.localAddress);
         socket = new MulticastSocket(new InetSocketAddress(whichNic, this.getAckPort()));
       }
       if (this.getSoReceiveBufferSize() > 0) {
         socket.setReceiveBufferSize(this.getSoReceiveBufferSize());
       }
     } else {
       socket = new MulticastSocket();
     }
     if (this.timeToLive >= 0) {
       socket.setTimeToLive(this.timeToLive);
     }
     setSocketAttributes(socket);
     if (localAddress != null) {
       InetAddress whichNic = InetAddress.getByName(this.localAddress);
       NetworkInterface intfce = NetworkInterface.getByInetAddress(whichNic);
       socket.setNetworkInterface(intfce);
     }
     this.setSocket(socket);
   }
 }
Пример #4
0
 public Object makeObject(Object key) throws Exception {
   ImmutableEndpoint ep = (ImmutableEndpoint) key;
   MulticastSocket socket = (MulticastSocket) super.makeObject(key);
   socket.setLoopbackMode(((MulticastConnector) ep.getConnector()).isLoopback());
   int ttl = ((MulticastConnector) ep.getConnector()).getTimeToLive();
   if (ttl != Connector.INT_VALUE_NOT_SET) {
     socket.setTimeToLive(ttl);
   }
   return socket;
 }
 @Override
 public void setTimeToLive(int ttl) {
   if (socket instanceof MulticastSocket) {
     try {
       ((MulticastSocket) socket).setTimeToLive(ttl);
     } catch (IOException e) {
       throw new ChannelException(e);
     }
   } else {
     throw new UnsupportedOperationException();
   }
 }
 /** INTERNAL: Create the multicast socket and join the multicast group. */
 public void createCommunicationSocket() {
   Object[] args = {multicastGroupAddress, "" + multicastPort};
   rcm.logDebug("initializing_discovery_resources", args);
   if (communicationSocket == null) {
     try {
       communicationSocket = new MulticastSocket(multicastPort);
       communicationSocket.setTimeToLive(getPacketTimeToLive());
       communicationSocket.joinGroup(InetAddress.getByName(multicastGroupAddress));
     } catch (IOException ex) {
       // Either we couldn't create the socket or we couldn't join the group
       DiscoveryException discoveryEx = DiscoveryException.errorJoiningMulticastGroup(ex);
       rcm.handleException(discoveryEx);
     }
   }
 }
Пример #7
0
  private void startMultiCastSocket() throws IOException {
    int bindPort = Discovery.DEFAULT_SSDP_SEARCH_PORT;
    String port = System.getProperty("net.sbbi.upnp.Discovery.bindPort");
    if (port != null) {
      bindPort = Integer.parseInt(port);
    }

    skt = new java.net.MulticastSocket(null);
    skt.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), bindPort));
    skt.setTimeToLive(Discovery.DEFAULT_TTL);
    skt.setSoTimeout(DEFAULT_TIMEOUT);
    skt.joinGroup(InetAddress.getByName(Discovery.SSDP_IP));

    byte[] buf = new byte[2048];
    input = new DatagramPacket(buf, buf.length);
  }
 public boolean send(String msg, String bindAddr, int bindPort) {
   try {
     MulticastSocket msock;
     if ((bindAddr) != null && (0 < bindPort)) {
       msock = new MulticastSocket(null);
       msock.bind(new InetSocketAddress(bindAddr, bindPort));
     } else msock = new MulticastSocket();
     DatagramPacket dgmPacket = new DatagramPacket(msg.getBytes(), msg.length(), ssdpMultiGroup);
     // Thnaks for Tho Beisch (11/09/04)
     msock.setTimeToLive(4);
     msock.send(dgmPacket);
     msock.close();
   } catch (Exception e) {
     Debug.warning(e);
     return false;
   }
   return true;
 }
Пример #9
0
  public void start() throws Exception {
    if (can_bind_to_mcast_addr) // https://jira.jboss.org/jira/browse/JGRP-836 - prevent cross
      // talking on Linux
      mcast_sock =
          Util.createMulticastSocket(
              getSocketFactory(), Global.MPING_MCAST_SOCK, mcast_addr, mcast_port, log);
    else mcast_sock = getSocketFactory().createMulticastSocket(Global.MPING_MCAST_SOCK, mcast_port);

    mcast_sock.setTimeToLive(ip_ttl);

    if (receive_on_all_interfaces
        || (receive_interfaces != null && !receive_interfaces.isEmpty())) {
      List<NetworkInterface> interfaces;
      if (receive_interfaces != null) interfaces = receive_interfaces;
      else interfaces = Util.getAllAvailableInterfaces();
      bindToInterfaces(interfaces, mcast_sock, mcast_addr);
    } else {
      if (bind_addr != null) mcast_sock.setInterface(bind_addr);
      mcast_sock.joinGroup(mcast_addr);
    }

    // 3b. Create mcast sender socket
    if (send_on_all_interfaces || (send_interfaces != null && !send_interfaces.isEmpty())) {
      List interfaces;
      NetworkInterface intf;
      if (send_interfaces != null) interfaces = send_interfaces;
      else interfaces = Util.getAllAvailableInterfaces();
      mcast_send_sockets = new MulticastSocket[interfaces.size()];
      int index = 0;
      for (Iterator it = interfaces.iterator(); it.hasNext(); ) {
        intf = (NetworkInterface) it.next();
        mcast_send_sockets[index] = new MulticastSocket();
        mcast_send_sockets[index].setNetworkInterface(intf);
        mcast_send_sockets[index].setTimeToLive(ip_ttl);
        index++;
      }
    }

    startReceiver();
    super.start();
  }
  @Before
  public void assumeMulticast() throws Exception {
    InetAddress multicastAddress = InetAddress.getByName("239.255.0.1");

    // Make sure receiver is setup before the sender, otherwise the packet gets lost
    MulticastSocket receiver = new MulticastSocket(0);
    receiver.joinGroup(multicastAddress);

    MulticastSocket sender = new MulticastSocket();
    sender.setTimeToLive(1);
    sender.send(
        new DatagramPacket(new byte[] {1}, 0, 1, multicastAddress, receiver.getLocalPort()));
    sender.close();

    byte[] buffer = new byte[1];
    receiver.setSoTimeout(1000);
    try {
      receiver.receive(new DatagramPacket(buffer, 0, buffer.length));
    } catch (SocketTimeoutException x) {
      Assume.assumeNoException(x);
    } finally {
      receiver.close();
    }
  }
  /**
   * Creates an array of sockets with TTL and network interface set.
   *
   * @param mcastTTL multicast TTL.
   * @return an array of multicast sockets to broadcast on.
   * @throws IOException if I/O error occurred while creating a multicast socket.
   * @noinspection SocketOpenedButNotSafelyClosed, ConstantConditions
   */
  private static MulticastSocket[] createSockets(final int mcastTTL) throws IOException {

    Exception lastException = null; // Records last error in case we could not create any sockets
    final List<MulticastSocket> socketList = new ArrayList<MulticastSocket>(11);
    final Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
    while (enumeration.hasMoreElements()) {
      try {
        final NetworkInterface netIf = enumeration.nextElement();
        final MulticastSocket socket = new MulticastSocket(); // NOPMD
        socket.setTimeToLive(mcastTTL);
        socket.setNetworkInterface(netIf);
        socket.setSendBufferSize(SEND_BUFFER_SIZE);
        socketList.add(socket);
      } catch (final Exception e) {
        lastException = e;
        ExceptionUtils.ignoreException(e, "continue to connect to those we can");
      }
    }
    if (socketList.isEmpty()) {
      throw new IOException(
          "Could not create at least one multicast socket. Last error: " + lastException);
    }
    return socketList.toArray(new MulticastSocket[socketList.size()]);
  }
Пример #12
0
  /**
   * Create UDP sender and receiver sockets. Currently there are 2 sockets (sending and receiving).
   * This is due to Linux's non-BSD compatibility in the JDK port (see DESIGN).
   */
  void createSockets() throws Exception {
    InetAddress tmp_addr = null;

    // bind_addr not set, try to assign one by default. This is needed on Windows

    // changed by bela Feb 12 2003: by default multicast sockets will be bound to all network
    // interfaces

    // CHANGED *BACK* by bela March 13 2003: binding to all interfaces did not result in a correct
    // local_addr. As a matter of fact, comparison between e.g. 0.0.0.0:1234 (on hostA) and
    // 0.0.0.0:1.2.3.4 (on hostB) would fail !
    if (bind_addr == null) {
      InetAddress[] interfaces =
          InetAddress.getAllByName(InetAddress.getLocalHost().getHostAddress());
      if (interfaces != null && interfaces.length > 0) bind_addr = interfaces[0];
    }

    if (bind_addr == null) bind_addr = InetAddress.getLocalHost();

    if (bind_addr != null && Trace.trace) {
      Trace.info(
          "UDP.createSockets()",
          "unicast sockets will use interface " + bind_addr.getHostAddress());

      // 2. Create socket for receiving unicast UDP packets. The address and port
      //    of this socket will be our local address (local_addr)

      // 27-6-2003 bgooren, find available port in range (start_port, start_port+port_range)
    }
    int rcv_port = bind_port, max_port = bind_port + port_range;
    while (rcv_port <= max_port) {

      try {
        sock = new DatagramSocket(rcv_port, bind_addr);
        break;
      } catch (SocketException bind_ex) { // Cannot listen on this port
        rcv_port++;
      } catch (SecurityException sec_ex) { // Not allowed to list on this port
        rcv_port++;
      }

      // Cannot listen at all, throw an Exception
      if (rcv_port == max_port + 1) { // +1 due to the increment above
        throw new Exception(
            "UDP.createSockets(): cannot list on any port in range "
                + bind_port
                + "-"
                + (bind_port + port_range));
      }
    }
    // ucast_recv_sock=new DatagramSocket(bind_port, bind_addr);
    if (sock == null) {
      throw new Exception("UDP.createSocket(): sock is null");
    }

    local_addr = new IpAddress(sock.getLocalAddress(), sock.getLocalPort());
    if (additional_data != null) {
      local_addr.setAdditionalData(additional_data);

      // 3. Create socket for receiving IP multicast packets
    }
    if (ip_mcast) {
      mcast_sock = new MulticastSocket(mcast_port);
      mcast_sock.setTimeToLive(ip_ttl);
      if (bind_addr != null) {
        mcast_sock.setInterface(bind_addr);
      }
      tmp_addr = InetAddress.getByName(mcast_addr_name);
      mcast_addr = new IpAddress(tmp_addr, mcast_port);
      mcast_sock.joinGroup(tmp_addr);
    }

    setBufferSizes();

    if (Trace.trace) {
      Trace.info("UDP.createSockets()", "socket information:\n" + dumpSocketInfo());
    }
  }
Пример #13
0
 public void setTimeToLive(int ttl) throws IOException {
   usock.setTimeToLive(ttl);
 }
Пример #14
0
  public void start(
      InetAddress addr,
      InetAddress bind_addr,
      int port,
      int ttl,
      final long timeout,
      List query,
      String match,
      boolean weed_out_duplicates)
      throws Exception {
    mcast_sock = new MulticastSocket();
    mcast_sock.setTimeToLive(ttl);
    if (bind_addr != null) mcast_sock.setInterface(bind_addr);

    StringBuilder request = new StringBuilder();
    for (int i = 0; i < query.size(); i++) {
      request.append(query.get(i)).append(" ");
    }
    byte[] probe_buf = request.toString().getBytes();

    DatagramPacket probe = new DatagramPacket(probe_buf, 0, probe_buf.length, addr, port);
    mcast_sock.send(probe);
    System.out.println("\n-- send probe on " + addr + ':' + port + '\n');

    new Thread() {
      public void run() {
        Util.sleep(timeout);
        mcast_sock.close();
        running = false;
      }
    }.start();

    int matched = 0, not_matched = 0, count = 0;
    String response;
    while (running) {
      byte[] buf = new byte[65000];
      DatagramPacket rsp = new DatagramPacket(buf, 0, buf.length);
      try {
        mcast_sock.receive(rsp);
      } catch (Throwable t) {
        System.out.println("\n");
        return;
      }

      byte[] data = rsp.getData();
      response = new String(data, 0, rsp.getLength());
      if (weed_out_duplicates && checkDuplicateResponse(response)) {
        continue;
      }

      if (matches(response, match)) {
        matched++;
        System.out.println("\n#" + ++count + " (" + rsp.getLength() + " bytes):\n" + response);
      } else not_matched++;
    }
    System.out.println(
        "\nTotal responses="
            + count
            + ", "
            + matched
            + " matches, "
            + not_matched
            + " non-matches");
  }
Пример #15
0
 public Node(HazelcastInstanceImpl hazelcastInstance, Config config, NodeContext nodeContext) {
   this.hazelcastInstance = hazelcastInstance;
   this.threadGroup = hazelcastInstance.threadGroup;
   this.config = config;
   configClassLoader = config.getClassLoader();
   this.groupProperties = new GroupProperties(config);
   SerializationService ss;
   try {
     ss =
         new SerializationServiceBuilder()
             .setClassLoader(configClassLoader)
             .setConfig(config.getSerializationConfig())
             .setManagedContext(hazelcastInstance.managedContext)
             .setHazelcastInstance(hazelcastInstance)
             .build();
   } catch (Exception e) {
     throw ExceptionUtil.rethrow(e);
   }
   serializationService = (SerializationServiceImpl) ss;
   systemLogService = new SystemLogService(groupProperties.SYSTEM_LOG_ENABLED.getBoolean());
   final AddressPicker addressPicker = nodeContext.createAddressPicker(this);
   try {
     addressPicker.pickAddress();
   } catch (Throwable e) {
     throw ExceptionUtil.rethrow(e);
   }
   final ServerSocketChannel serverSocketChannel = addressPicker.getServerSocketChannel();
   address = addressPicker.getPublicAddress();
   localMember = new MemberImpl(address, true, UuidUtil.createMemberUuid(address));
   String loggingType = groupProperties.LOGGING_TYPE.getString();
   loggingService =
       new LoggingServiceImpl(
           systemLogService, config.getGroupConfig().getName(), loggingType, localMember);
   logger = loggingService.getLogger(Node.class.getName());
   initializer = NodeInitializerFactory.create(configClassLoader);
   try {
     initializer.beforeInitialize(this);
   } catch (Throwable e) {
     try {
       serverSocketChannel.close();
     } catch (Throwable ignored) {
     }
     throw ExceptionUtil.rethrow(e);
   }
   securityContext =
       config.getSecurityConfig().isEnabled() ? initializer.getSecurityContext() : null;
   nodeEngine = new NodeEngineImpl(this);
   clientEngine = new ClientEngineImpl(this);
   connectionManager = nodeContext.createConnectionManager(this, serverSocketChannel);
   partitionService = new PartitionServiceImpl(this);
   clusterService = new ClusterServiceImpl(this);
   textCommandService = new TextCommandServiceImpl(this);
   initializer.printNodeInfo(this);
   buildNumber = initializer.getBuildNumber();
   VersionCheck.check(this, initializer.getBuild(), initializer.getVersion());
   JoinConfig join = config.getNetworkConfig().getJoin();
   MulticastService mcService = null;
   try {
     if (join.getMulticastConfig().isEnabled()) {
       MulticastConfig multicastConfig = join.getMulticastConfig();
       MulticastSocket multicastSocket = new MulticastSocket(null);
       multicastSocket.setReuseAddress(true);
       // bind to receive interface
       multicastSocket.bind(new InetSocketAddress(multicastConfig.getMulticastPort()));
       multicastSocket.setTimeToLive(multicastConfig.getMulticastTimeToLive());
       try {
         // set the send interface
         final Address bindAddress = addressPicker.getBindAddress();
         // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4417033
         // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6402758
         if (!bindAddress.getInetAddress().isLoopbackAddress()) {
           multicastSocket.setInterface(bindAddress.getInetAddress());
         }
       } catch (Exception e) {
         logger.warning(e);
       }
       multicastSocket.setReceiveBufferSize(64 * 1024);
       multicastSocket.setSendBufferSize(64 * 1024);
       String multicastGroup = System.getProperty("hazelcast.multicast.group");
       if (multicastGroup == null) {
         multicastGroup = multicastConfig.getMulticastGroup();
       }
       multicastConfig.setMulticastGroup(multicastGroup);
       multicastSocket.joinGroup(InetAddress.getByName(multicastGroup));
       multicastSocket.setSoTimeout(1000);
       mcService = new MulticastService(this, multicastSocket);
       mcService.addMulticastListener(new NodeMulticastListener(this));
     }
   } catch (Exception e) {
     logger.severe(e);
   }
   this.multicastService = mcService;
   initializeListeners(config);
   joiner = nodeContext.createJoiner(this);
 }