Exemple #1
0
  void setBufferSizes() {
    if (sock != null) {
      try {
        sock.setSendBufferSize(ucast_send_buf_size);
      } catch (Throwable ex) {
        Trace.warn("UDP.setBufferSizes()", "failed setting ucast_send_buf_size in sock: " + ex);
      }
      try {
        sock.setReceiveBufferSize(ucast_recv_buf_size);
      } catch (Throwable ex) {
        Trace.warn("UDP.setBufferSizes()", "failed setting ucast_recv_buf_size in sock: " + ex);
      }
    }

    if (mcast_sock != null) {
      try {
        mcast_sock.setSendBufferSize(mcast_send_buf_size);
      } catch (Throwable ex) {
        Trace.warn(
            "UDP.setBufferSizes()", "failed setting mcast_send_buf_size in mcast_sock: " + ex);
      }

      try {
        mcast_sock.setReceiveBufferSize(mcast_recv_buf_size);
      } catch (Throwable ex) {
        Trace.warn(
            "UDP.setBufferSizes()", "failed setting mcast_recv_buf_size in mcast_sock: " + ex);
      }
    }
  }
  /**
   * Sends a leave message to the multicast group and leaves it. The <CODE>DiscoveryResponder</CODE>
   * leaves its multicast group. This method has no effect if the <CODE>DiscoveryResponder</CODE> is
   * <CODE>OFFLINE</CODE> or <CODE>STOPPING</CODE> or <CODE>STARTING</CODE>.
   */
  public void stop() {
    if (state == ONLINE) {
      changeState(STOPPING);
      // ------------------------
      // Stop corresponding thread
      // ------------------------

      responder.stopRequested = true;

      synchronized (responder.interrupted) {
        if (!responder.interrupted.booleanValue()) {
          responderThread.interrupt();
        }
      }

      // Fix for cases when the interrupt does not work (Windows NT)
      try {
        MulticastSocket ms = new MulticastSocket(multicastPort);

        // NPCTE fix for bugId 4499338, esc 0, 04 Sept 2001
        if (usrInet != null) {
          ms.setInterface(usrInet);

          if (logger.finerOn()) {
            logger.finer("stop ", "use the interface " + usrInet);
          }
        }
        // end of NPCTE fix for bugId 4499338

        InetAddress group = InetAddress.getByName(multicastGroup);
        ms.joinGroup(group);
        ms.send(new DatagramPacket(new byte[1], 1, group, multicastPort));
        ms.leaveGroup(group);
      } catch (Exception e) {
        if (logger.finerOn()) {
          logger.finer(
              "stop ",
              "Unexpected exception occurred trying to send empty message " + e.getMessage());
        }
      }

      // ------------------------
      // free 'remained' allocated resource
      // ------------------------
      responder = null;
      System.runFinalization();

      // ----------------
      // Update state
      // ----------------
      // changeState(OFFLINE) ;
    } else {
      if (logger.finerOn()) {
        logger.finer("stop ", "Responder is not ONLINE");
      }
    }
  }
  public boolean open(String addr, int port, String bindAddr) {
    try {
      ssdpMultiSock = new MulticastSocket(null);
      ssdpMultiSock.setReuseAddress(true);
      InetSocketAddress bindSockAddr = new InetSocketAddress(port);
      ssdpMultiSock.bind(bindSockAddr);
      ssdpMultiGroup = new InetSocketAddress(InetAddress.getByName(addr), port);
      ssdpMultiIf = NetworkInterface.getByInetAddress(InetAddress.getByName(bindAddr));
      ssdpMultiSock.joinGroup(ssdpMultiGroup, ssdpMultiIf);
    } catch (Exception e) {
      Debug.warning(e);
      return false;
    }

    return true;
  }
 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;
 }
Exemple #5
0
 void closeMulticastSocket() {
   if (mcast_sock != null) {
     try {
       if (mcast_addr != null) {
         // by sending a dummy packet the thread will be awakened
         sendDummyPacket(mcast_addr.getIpAddress(), mcast_addr.getPort());
         Util.sleep(300);
         mcast_sock.leaveGroup(mcast_addr.getIpAddress());
       }
       mcast_sock.close(); // this will cause the mcast receiver thread to break out of its loop
       mcast_sock = null;
       if (Trace.trace) {
         Trace.info("UDP.closeMulticastSocket()", "multicast socket closed");
       }
     } catch (IOException ex) {
     }
     mcast_addr = null;
   }
 }
 public SSDPPacket receive() {
   byte ssdvRecvBuf[] = new byte[SSDP.RECV_MESSAGE_BUFSIZE];
   SSDPPacket recvPacket = new SSDPPacket(ssdvRecvBuf, ssdvRecvBuf.length);
   recvPacket.setLocalAddress(getLocalAddress());
   try {
     ssdpMultiSock.receive(recvPacket.getDatagramPacket());
     recvPacket.setTimeStamp(System.currentTimeMillis());
   } catch (Exception e) {
     // Debug.warning(e);
   }
   return recvPacket;
 }
Exemple #7
0
  public static void main(String[] args) throws IOException {

    MulticastSocket socket = new MulticastSocket(4446);
    InetAddress address = InetAddress.getByName("230.0.0.1");
    socket.joinGroup(address);

    DatagramPacket packet;

    // get a few quotes
    for (int i = 0; i < 5; i++) {

      byte[] buf = new byte[256];
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);

      String received = new String(packet.getData(), 0, packet.getLength());
      System.out.println("Quote of the Moment: " + received);
    }

    socket.leaveGroup(address);
    socket.close();
  }
  public boolean close() {
    if (ssdpMultiSock == null) return true;

    try {
      ssdpMultiSock.leaveGroup(ssdpMultiGroup, ssdpMultiIf);
      ssdpMultiSock = null;
    } catch (Exception e) {
      // Debug.warning(e);
      return false;
    }

    return true;
  }
Exemple #9
0
  String dumpSocketInfo() throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.append("local_addr=").append(local_addr);
    sb.append(", mcast_addr=").append(mcast_addr);
    sb.append(", bind_addr=").append(bind_addr);
    sb.append(", ttl=").append(ip_ttl);

    if (sock != null) {
      sb.append("\nsocket: bound to ");
      sb.append(sock.getLocalAddress().getHostAddress()).append(":").append(sock.getLocalPort());
      sb.append(", receive buffer size=").append(sock.getReceiveBufferSize());
      sb.append(", send buffer size=").append(sock.getSendBufferSize());
    }

    if (mcast_sock != null) {
      sb.append("\nmulticast socket: bound to ");
      sb.append(mcast_sock.getInterface().getHostAddress())
          .append(":")
          .append(mcast_sock.getLocalPort());
      sb.append(", send buffer size=").append(mcast_sock.getSendBufferSize());
      sb.append(", receive buffer size=").append(mcast_sock.getReceiveBufferSize());
    }
    return sb.toString();
  }
  public void destory() {
    procMsgThd.stop0();
    procMsgThd.interrupt();
    mainThread.interrupt();
    if (group != null) {
      try {
        if (recvSocket instanceof MulticastSocket) {
          ((MulticastSocket) recvSocket).leaveGroup(group);
        }
      } catch (IOException ioe) {
      }
    }

    sendSocket.close();
    recvSocket.close();
  }
  public void initGroup() throws UDPBaseException {
    try {
      mainThread = new SoleThread(this);

      sendSocket = new DatagramSocket();
      recvSocket = new MulticastSocket(RECV_PORT);
      // recvAckSocket = new MulticastSocket (RECV_ACK_PORT) ;
      group = InetAddress.getByName(GROUP_BROADCAST_ADDR);
      ((MulticastSocket) recvSocket).joinGroup(group);
      // recvAckSocket.joinGroup (group) ;
      localIP = InetAddress.getLocalHost().getHostAddress();

      procMsgThd = new ProcMsgThd();
      procMsgThd.start();
      //
      mainThread.start();

      bGroup = true;
    } catch (Exception e) {
      e.printStackTrace();
      throw new UDPBaseException("UDPBase init() error=\n" + e.toString());
    }
  }
  public void initVirtual(String virtualip) throws UDPBaseException {
    if (virtualip == null) {
      virtualip = "vip:" + System.currentTimeMillis();
    }
    try {
      mainThread = new SoleThread(this);

      sendSocket = new DatagramSocket();
      recvSocket = new MulticastSocket(RECV_PORT);
      // recvAckSocket = new MulticastSocket (RECV_ACK_PORT) ;
      group = InetAddress.getByName(GROUP_BROADCAST_ADDR);
      ((MulticastSocket) recvSocket).joinGroup(group);
      // recvAckSocket.joinGroup (group) ;
      localIP = virtualip;

      procMsgThd = new ProcMsgThd();
      procMsgThd.start();
      //
      mainThread.start();
    } catch (Exception e) {
      e.printStackTrace();
      throw new UDPBaseException("UDPBase init() error=\n" + e.toString());
    }
  }
Exemple #13
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());
    }
  }
Exemple #14
0
  public void run() {
    DatagramPacket packet;
    byte receive_buf[] = new byte[65535];
    int len;
    byte[] tmp, data;

    // moved out of loop to avoid excessive object creations (bela March 8 2001)
    packet = new DatagramPacket(receive_buf, receive_buf.length);

    while (mcast_receiver != null && mcast_sock != null) {
      try {
        packet.setData(receive_buf, 0, receive_buf.length);
        mcast_sock.receive(packet);
        len = packet.getLength();
        data = packet.getData();
        if (len == 1 && data[0] == 0) {
          if (Trace.debug) {
            Trace.info("UDP.run()", "received dummy packet");
          }
          continue;
        }

        if (len == 4) { // received a diagnostics probe
          if (data[0] == 'd' && data[1] == 'i' && data[2] == 'a' && data[3] == 'g') {
            handleDiagnosticProbe(packet.getAddress(), packet.getPort());
            continue;
          }
        }

        if (Trace.debug) {
          Trace.info(
              "UDP.receive()",
              "received (mcast) "
                  + packet.getLength()
                  + " bytes from "
                  + packet.getAddress()
                  + ":"
                  + packet.getPort()
                  + " (size="
                  + len
                  + " bytes)");
        }
        if (len > receive_buf.length) {
          Trace.error(
              "UDP.run()",
              "size of the received packet ("
                  + len
                  + ") is bigger than "
                  + "allocated buffer ("
                  + receive_buf.length
                  + "): will not be able to handle packet. "
                  + "Use the FRAG protocol and make its frag_size lower than "
                  + receive_buf.length);
        }

        if (Version.compareTo(data) == false) {
          Trace.warn(
              "UDP.run()",
              "packet from "
                  + packet.getAddress()
                  + ":"
                  + packet.getPort()
                  + " has different version ("
                  + Version.printVersionId(data, Version.version_id.length)
                  + ") from ours ("
                  + Version.printVersionId(Version.version_id)
                  + "). This may cause problems");
        }

        if (use_incoming_packet_handler) {
          tmp = new byte[len];
          System.arraycopy(data, 0, tmp, 0, len);
          incoming_queue.add(tmp);
        } else {
          handleIncomingUdpPacket(data);
        }
      } catch (SocketException sock_ex) {
        if (Trace.trace) {
          Trace.info("UDP.run()", "multicast socket is closed, exception=" + sock_ex);
        }
        break;
      } catch (InterruptedIOException io_ex) { // thread was interrupted
        ; // go back to top of loop, where we will terminate loop
      } catch (Throwable ex) {
        Trace.error("UDP.run()", "exception=" + ex + ", stack trace=" + Util.printStackTrace(ex));
        Util.sleep(300); // so we don't get into 100% cpu spinning (should NEVER happen !)
      }
    }
    if (Trace.trace) {
      Trace.info("UDP.run()", "multicast thread terminated");
    }
  }
  public static void main(String args[]) throws Exception {
    DatagramSocket r_clients = null, s_clients = null;
    MulticastSocket servers = null, b_clients = null;

    local = Integer.parseInt(args[1]);
    rec = Integer.parseInt(args[0]);

    System.out.println("Recieving arp on port " + rec + "...");
    System.out.println("Recieving reply arp on port " + (rec + 1) + "...");
    System.out.println("\nEmulating gateway on port " + local + "\nWaiting...");

    try {
      r_clients = new DatagramSocket(rec);

      s_clients = new DatagramSocket(rec + 1);

      b_clients = new MulticastSocket(local);
      b_clients.joinGroup(InetAddress.getByName(group));

      servers = new MulticastSocket(serv_port);
      servers.joinGroup(InetAddress.getByName(group));

      servers.setSoTimeout(10);
      s_clients.setSoTimeout(10);
      b_clients.setSoTimeout(10);
      r_clients.setSoTimeout(10);
    } catch (Exception e) {
      System.out.println("error: " + e.toString());
      System.exit(1);
    }

    byte arp_buf[] = new byte[28];
    DatagramPacket arp_packet = new DatagramPacket(arp_buf, arp_buf.length);

    while (true) {
      try {
        servers.receive(arp_packet);
        System.out.println("\nGot arp from servers");

        System.out.println("Sending arp to local computers");
        arp_packet.setAddress(InetAddress.getByName(group));
        arp_packet.setPort(local);
        try {
          b_clients.send(arp_packet, (byte) 255);
        } catch (Exception e3) {
        }
      } catch (Exception e) {
        try {
          r_clients.receive(arp_packet);
          System.out.println("\nGot arp from client");

          System.out.println("Sending ARP");
          arp_packet.setAddress(InetAddress.getByName(group));
          arp_packet.setPort(serv_port);
          try {
            servers.send(arp_packet, (byte) 255);
          } catch (Exception e3) {
          }
        } catch (Exception e2) {
          try {
            s_clients.receive(arp_packet);
            System.out.println("\nGot reply arp from client");

            arp_packet.setAddress(InetAddress.getByName(group));
            arp_packet.setPort(2500);
            try {
              s_clients.send(arp_packet);
            } catch (Exception e3) {
            }
          } catch (Exception e4) {
          }
        }
      }
    }
  }