/**
   * Constructor. Creates a datagram send socket and connects it to the Ganglia hypertable extension
   * listen port. Initializes mPrefix to "ht." + <code>component</code> + ".".
   *
   * @param component Hypertable component ("fsbroker", "hyperspace, "master", "rangeserver", or
   *     "thriftbroker")
   * @param props Configuration properties
   */
  public MetricsCollectorGanglia(String component, Properties props) {
    mPrefix = "ht." + component + ".";

    String str = props.getProperty("Hypertable.Metrics.Ganglia.Port", "15860");
    mPort = Integer.parseInt(str);

    str = props.getProperty("Hypertable.Metrics.Ganglia.Disabled");
    if (str != null && str.equalsIgnoreCase("true")) mDisabled = true;

    try {
      mAddr = InetAddress.getByName("localhost");
    } catch (UnknownHostException e) {
      System.out.println("UnknownHostException : 'localhost'");
      e.printStackTrace();
      System.exit(-1);
    }

    try {
      mSocket = new DatagramSocket();
    } catch (SocketException e) {
      e.printStackTrace();
      System.exit(-1);
    }

    mSocket.connect(mAddr, mPort);
    mConnected = true;
  }
Ejemplo n.º 2
0
  public void sendToClient(byte[] buffer, String ip) {

    String[] strings = ip.split(":");

    try {
      DatagramPacket packet =
          new DatagramPacket(
              buffer,
              buffer.length,
              new InetSocketAddress(strings[0], Integer.parseInt(strings[1])));

      if (PearCtrl.localUrl.contains(strings[0])) {
        socket.send(packet);
      } else {
        Burrow burrow = new Burrow(socket, packet);

        hashMap.put(ip, burrow);
      }

    } catch (SocketException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (IOException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
Ejemplo n.º 3
0
  public void run() {
    System.out.println("ExeUDPServer开始监听..." + UDP_PORT);
    DatagramSocket ds = null;
    try {
      ds = new DatagramSocket(UDP_PORT);
    } catch (BindException e) {
      System.out.println("UDP端口使用中...请重关闭程序启服务器");
    } catch (SocketException e) {
      e.printStackTrace();
    }

    while (ds != null) {
      DatagramPacket dp = new DatagramPacket(buf, buf.length);
      try {
        ds.receive(dp);
        // 得到把该数据包发来的端口和Ip
        int rport = dp.getPort();
        InetAddress addr = dp.getAddress();
        String recvStr = new String(dp.getData(), 0, dp.getLength());
        System.out.println("Server receive:" + recvStr + " from " + addr + "  " + rport);

        // 给客户端回应
        String sendStr = "echo of " + recvStr;
        byte[] sendBuf;
        sendBuf = sendStr.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, rport);
        ds.send(sendPacket);

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Ejemplo n.º 4
0
    public void run() {

      while (!isThreadRunning) {

        byte[] ack_byte = new byte[2];

        DatagramPacket packet_ack = new DatagramPacket(ack_byte, ack_byte.length);
        try {
          socketAck.setSoTimeout(5);
        } catch (SocketException e) {
          e.printStackTrace();
        }
        try {
          socketAck.receive(packet_ack);
        } catch (IOException e) {
          e.printStackTrace();
        }
        byte[] ackData = packet_ack.getData();
        int packet_ack_num = getAckPaket(ackData);
        num_acked = Math.max(num_acked, packet_ack_num);
        Thread.yield();
      }

      socketAck.close();
    }
Ejemplo n.º 5
0
  private static String getNetworkInterface() {

    String networkInterfaceName =
        ">>>> modify networkInterface in us.codecraft.webmagic.utils.ProxyUtils";
    Enumeration<NetworkInterface> enumeration = null;
    try {
      enumeration = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e1) {
      e1.printStackTrace();
    }
    while (enumeration.hasMoreElements()) {
      NetworkInterface networkInterface = enumeration.nextElement();

      Enumeration<InetAddress> addr = networkInterface.getInetAddresses();
      while (addr.hasMoreElements()) {
        String s = addr.nextElement().getHostAddress();
        Pattern IPV4_PATTERN =
            Pattern.compile(
                "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
        if (s != null && IPV4_PATTERN.matcher(s).matches()) {
          networkInterfaceName += networkInterface.toString() + "IP:" + s + "\n\n";
        }
      }
    }
    return networkInterfaceName;
  }
Ejemplo n.º 6
0
    public void run() {
      try {
        out = new PrintWriter(this.socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));

        while (true) {
          synchronized (this) {
            out.println(HEARTBEAT);
          }
          reallySleep(NORMAL_HEARTBEAT_INTERVAL);
        }
      } catch (SocketException e) {
        log("Socket Exception: client may have already shutdown.");
        log(e.getClass() + ": " + Arrays.asList(e.getStackTrace()));
      } catch (Exception e) {
        log("Heartbeat thread for child process (port " + port + ") got exception");
        log(e.getClass() + ": " + Arrays.asList(e.getStackTrace()));
      } finally {
        log("Heartbeat thread for child process (port " + port + ") terminating.");
        try {
          socket.close();
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
Ejemplo n.º 7
0
  public static String getIPaddress() {
    try {
      for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
          en.hasMoreElements(); ) {

        NetworkInterface interf = en.nextElement();

        for (Enumeration<InetAddress> enumIpAddr = interf.getInetAddresses();
            enumIpAddr.hasMoreElements(); ) {

          InetAddress inetAddress = enumIpAddr.nextElement();

          if (!inetAddress.isLoopbackAddress()) {

            String ipAddres = inetAddress.getHostAddress().toString();
            Log.e("ip address: ", ipAddres);
            return ipAddres;
          }
        }
      }
    } catch (SocketException ex) {
      Log.e("SOCKET EXCEPTION in get IP ADDDRESs", ex.toString());
    }
    return null;
  }
Ejemplo n.º 8
0
  public PingResult ping(ScanningSubject subject, int count) throws IOException {
    PingResult result = new PingResult(subject.getAddress());

    DatagramSocket socket = sockets.bind(new DatagramSocket());
    socket.setSoTimeout(timeout);
    socket.connect(subject.getAddress(), PROBE_UDP_PORT);

    for (int i = 0; i < count && !Thread.currentThread().isInterrupted(); i++) {
      long startTime = System.currentTimeMillis();
      byte[] payload = new byte[8];
      ByteBuffer.wrap(payload).putLong(startTime);
      DatagramPacket packet = new DatagramPacket(payload, payload.length);
      try {
        socket.send(packet);
        socket.receive(packet);
      } catch (PortUnreachableException e) {
        result.addReply(System.currentTimeMillis() - startTime);
      } catch (SocketTimeoutException ignore) {
      } catch (NoRouteToHostException e) {
        // this means that the host is down
        break;
      } catch (SocketException e) {
        if (e.getMessage().contains(/*No*/ "route to host")) {
          // sometimes 'No route to host' also gets here...
          break;
        }
      } catch (IOException e) {
        LOG.log(FINER, subject.toString(), e);
      }
    }
    return result;
  }
Ejemplo n.º 9
0
  public static void main(String[] args) {
    if (args.length == 0) {
      System.err.println("Usage: ntp.NTPClient <hostname-or-address-list>");
      System.exit(1);
    }

    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);
    try {
      client.open();
      for (String arg : args) {
        System.out.println();
        try {
          InetAddress hostAddr = InetAddress.getByName(arg);
          System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
          TimeInfo info = client.getTime(hostAddr);
          processResponse(info);
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }
      }
    } catch (SocketException e) {
      e.printStackTrace();
    }

    client.close();
  }
Ejemplo n.º 10
0
 /** Sends the next speakable to Avatar. */
 private void sendNextSpeakable() {
   final QueuedSpeakable next = speakables.peek();
   final SpeakableText speakable = next.getSpeakable();
   final String utterance;
   final SsmlDocument document;
   if (speakable instanceof SpeakableSsmlText) {
     final SpeakableSsmlText ssml = (SpeakableSsmlText) speakable;
     document = ssml.getDocument();
     final Speak speak = document.getSpeak();
     utterance = speak.getTextContent();
   } else {
     utterance = speakable.getSpeakableText();
     document = null;
   }
   ErrorEvent error = null;
   try {
     final String bml = createBML(utterance, document);
     sendToAvatar(bml);
   } catch (SocketException e) {
     error = new BadFetchError(e.getMessage(), e);
   } catch (UnknownHostException e) {
     error = new BadFetchError(e.getMessage(), e);
   } catch (IOException e) {
     error = new BadFetchError(e.getMessage(), e);
   } catch (XMLStreamException e) {
     error = new BadFetchError(e.getMessage(), e);
   }
   if (error != null) {
     synchronized (listeners) {
       for (SynthesizedOutputListener listener : listeners) {
         listener.outputError(error);
       }
     }
   }
 }
Ejemplo n.º 11
0
 public static void main(String[] argu) {
   try {
     new PureDNSListener().run();
   } catch (SocketException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 12
0
  // on linux system
  public void init2() {
    try {
      NetworkInterface networkInterface = NetworkInterface.getByName("eth0");
      Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
      while (inetAddresses.hasMoreElements()) {
        InetAddress address = inetAddresses.nextElement();
        if (!address.isLinkLocalAddress()) { // just get IPv4 address
          localAddress = address;
        }
      }
      // get broadcast address
      List<InterfaceAddress> addresses = networkInterface.getInterfaceAddresses();
      for (InterfaceAddress address : addresses) {
        if (address.getBroadcast() != null) {
          broadcastAddress = address.getBroadcast();
          break;
        }
      }
      if (broadcastAddress == null) {
        System.out.println("get broadcast address error!");
      }
      System.out.println("local ip address is " + localAddress.getHostAddress());
      System.out.println("broadcast address is " + broadcastAddress.getHostAddress());

      socket = new DatagramSocket();
      socket.setBroadcast(true);
    } catch (SocketException se) {
      se.printStackTrace();
    }
  }
Ejemplo n.º 13
0
  public void init() {
    try {
      localAddress = InetAddress.getLocalHost();
      if (localAddress.isLoopbackAddress()) {
        System.out.println("get local ip error!");
        return;
      }
      NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localAddress);
      List<InterfaceAddress> addresses = networkInterface.getInterfaceAddresses();
      for (InterfaceAddress address : addresses) {
        if (address.getAddress() instanceof Inet6Address) {
          continue;
        }
        if (address.getBroadcast() != null) {
          broadcastAddress = address.getBroadcast();
          break;
        } else {
          System.out.println("get broadcast address error!");
        }
      }
      System.out.println("local ip address is " + localAddress.getHostAddress());
      System.out.println("broadcast address is " + broadcastAddress.getHostAddress());

      socket = new DatagramSocket(2000);
      socket.setBroadcast(true);

    } catch (UnknownHostException ue) {
      ue.printStackTrace();
    } catch (SocketException se) {
      se.printStackTrace();
    }
  }
Ejemplo n.º 14
0
  public static String FindIP() {

    Enumeration<NetworkInterface> interfaces = null;
    try {
      interfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
      e.printStackTrace();
    }

    while (interfaces.hasMoreElements()) {
      NetworkInterface ifc = interfaces.nextElement();

      if (ifc.getName().equals("ppp" + myDigit)) {
        try {
          if (ifc.isUp()) {

            List<InterfaceAddress> ia = ifc.getInterfaceAddresses();
            System.out.println("IFC ip" + ia.get(0).getAddress().toString());
            return ia.get(0).getAddress().toString();
          }
        } catch (SocketException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
    return null;
  }
Ejemplo n.º 15
0
  // Print IP addresses and network interfaces
  private static void printIPAddresses() {
    try {
      InetAddress localhost = InetAddress.getLocalHost();
      System.out.println("Server: IP Address: " + localhost.getHostAddress());
      // Just in case this host has multiple IP addresses....
      InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
      if (allMyIps != null && allMyIps.length > 1) {
        System.out.println("Server: Full list of IP addresses:");
        for (InetAddress allMyIp : allMyIps) {
          System.out.println("    " + allMyIp);
        }
      }
    } catch (UnknownHostException ex) {
      System.out.println("Server: Cannot get IP address of local host");
      System.out.println("Server: UnknownHostException: " + ex.getMessage());
    }

    try {
      System.out.println("Server: Full list of network interfaces:");
      for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
          en.hasMoreElements(); ) {
        NetworkInterface intf = en.nextElement();
        System.out.println("    " + intf.getName() + " " + intf.getDisplayName());
        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
            enumIpAddr.hasMoreElements(); ) {
          System.out.println("        " + enumIpAddr.nextElement().toString());
        }
      }
    } catch (SocketException ex) {
      System.out.println("Server: Cannot retrieve network interface list");
      System.out.println("Server: UnknownHostException: " + ex.getMessage());
    }
  }
Ejemplo n.º 16
0
 static {
   try {
     mClient = new DatagramSocket();
   } catch (SocketException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 17
0
    @Override
    protected Void doInBackground(Void... params) {

      try {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {

          NetworkInterface thisInterface = networkInterfaces.nextElement();
          Enumeration<InetAddress> inetAddresses = thisInterface.getInetAddresses();
          if (inetAddresses.hasMoreElements()) {
            String niInfo = thisInterface.getDisplayName() + "\n";

            while (inetAddresses.hasMoreElements()) {
              InetAddress thisAddress = inetAddresses.nextElement();
              niInfo += "---\n";
              niInfo += "Address: " + thisAddress.getAddress() + "\n";
              niInfo += "CanonicalHostName: " + thisAddress.getCanonicalHostName() + "\n";
              niInfo += "HostAddress: " + thisAddress.getHostAddress() + "\n";
              niInfo += "HostName: " + thisAddress.getHostName() + "\n";
            }

            publishProgress(niInfo);
          }
        }
      } catch (SocketException e) {
        e.printStackTrace();
      }
      return null;
    }
 public DroneSocketClient(String serverAddress, int clientPort, int serverPort, int pingPort)
     throws DroneSocketClientException {
   this.serverAddress = serverAddress;
   this.clientPort = clientPort;
   this.pingPort = pingPort;
   this.serverPort = serverPort;
   try {
     srvAddr = InetAddress.getByName(serverAddress);
   } catch (UnknownHostException e) {
     if (DEBUG) {
       e.printStackTrace();
       Log.d(TAG, "ERROR: UNKNOWN HOST!");
       throw new DroneSocketClientException("");
     }
   }
   try {
     clientSocket = new DatagramSocket(clientPort);
     clientSocket.setSoTimeout(packetTIMEOUT);
   } catch (SocketException e) {
     if (DEBUG) {
       e.printStackTrace();
       Log.d(TAG, "CLIENTSOCKET BIND ERROR!");
       throw new DroneSocketClientException("");
     }
   }
   inData = new byte[1024];
   outData = new byte[1024];
   outPacket = new DatagramPacket(outData, outData.length, srvAddr, serverPort);
   inPacket = new DatagramPacket(inData, inData.length);
 }
Ejemplo n.º 19
0
 public void setSoTimeout(int timeout) {
   try {
     _socket.setSoTimeout(timeout);
   } catch (SocketException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 20
0
  public void send(DatagramSocket ds, String IP, int port) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);

    try {
      dos.writeInt(msgType); // 消息类型
      dos.writeUTF(id); // 用户id
      dos.writeUTF(name); // 用户名
      dos.writeUTF(token); // 用户名

    } catch (IOException e1) {
      e1.printStackTrace();
    }

    byte[] buffer = baos.toByteArray();

    try {

      DatagramPacket dp =
          new DatagramPacket(buffer, buffer.length, new InetSocketAddress(IP, port));
      ds.send(dp);

    } catch (SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 21
0
  /**
   * This method created a socket and a packet. It is performed only once in
   *
   * <p>the constructor of JoyActivity.
   *
   * <p>Indeed, two objects are required for UDP communication, a socket and a
   *
   * <p>packet as respective class DatagramSocket and DatagramPacket (classes
   *
   * <p>available in the Android libraries).
   *
   * @param ComandeUDP start command
   * @param port The Port to use
   * @param host The Address IP target
   */
  public DatagramSocket CreationSocketPacket(String ComandeUDP, int port, String host) {
    buffer = new byte[512];

    try { // TRY CREATION SOCKET
      udp_socket = new DatagramSocket();

    } catch (SocketException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    try { // INSERTION TRAME
      buffer = ComandeUDP.concat("\r").getBytes("ASCII");

    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    try { // INSERTION ADRESSE
      adresse = InetAddress.getByName(host);
    } catch (UnknownHostException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    udp_packet = new DatagramPacket(buffer, buffer.length, adresse, port);
    return udp_socket;
  }
Ejemplo n.º 22
0
  private void serviceClient(Socket clientSocket) {
    IHttpRequest request;
    IHttpResponse response;

    // pour éviter un blocage dans le serveur
    try {
      clientSocket.setSoTimeout(10000);
    } catch (SocketException e) {
      logger.error(e.getMessage());
      try {
        clientSocket.close();
      } catch (IOException e1) {
        logger.error(e1.getMessage());
      }
      return;
    }

    HttpClient httpClient = new HttpClient(clientSocket);

    try {
      request = httpClient.getHttpRequest();
      logger.info("receive :\n" + request);
      response = process.run(request);
    } catch (IOException | MethodeTypeException e) {
      logger.error(e.getMessage());
      response = DefaultResponseFactory.createResponseBadRequestException(e);
    }

    httpClient.sendHttpResponse(response);
    httpClient.shutdown();
  }
  /** Initializes the query system by binding it to a port */
  private boolean initQuerySystem() {
    try {
      querySocket = new DatagramSocket(queryPort, InetAddress.getByName(serverHostname));
      registerSocket(querySocket);
      querySocket.setSoTimeout(500);
      return true;
    } catch (SocketException var2) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (Socket): "
              + var2.getMessage());
    } catch (UnknownHostException var3) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (Unknown Host): "
              + var3.getMessage());
    } catch (Exception var4) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (E): "
              + var4.getMessage());
    }

    return false;
  }
 /** Start the thread. Exits when the client has been completely handled. */
 @Override
 public void run() {
   try {
     GELFClientHandlerIF client = null;
     if (GELF.isChunkedMessage(this.receivedGelfSentence)) {
       LOG.info("Received message is chunked. Handling now.");
       client = new ChunkedGELFClientHandler(this.receivedGelfSentence);
     } else {
       LOG.info("Received message is not chunked. Handling now.");
       client = new SimpleGELFClientHandler(this.receivedGelfSentence);
     }
     client.handle();
   } catch (InvalidGELFTypeException e) {
     LOG.error("Invalid GELF type in message: " + e.getMessage(), e);
   } catch (InvalidGELFHeaderException e) {
     LOG.error("Invalid GELF header in message: " + e.getMessage(), e);
   } catch (InvalidGELFCompressionMethodException e) {
     LOG.error("Invalid compression method of GELF message: " + e.getMessage(), e);
   } catch (java.util.zip.DataFormatException e) {
     LOG.error("Invalid compression data format in GELF message: " + e.getMessage(), e);
   } catch (java.io.UnsupportedEncodingException e) {
     LOG.error("Invalid enconding of GELF message: " + e.getMessage(), e);
   } catch (java.io.EOFException e) {
     LOG.error("EOF Exception while handling GELF message: " + e.getMessage(), e);
   } catch (java.net.SocketException e) {
     LOG.error("SocketException while handling GELF message: " + e.getMessage(), e);
   } catch (java.io.IOException e) {
     LOG.error("IO Error while handling GELF message: " + e.getMessage(), e);
   } catch (Exception e) {
     LOG.error("Exception caught while handling GELF message: " + e.getMessage(), e);
   }
 }
Ejemplo n.º 25
0
  private Core() {
    boolean f = false;
    try {
      for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
        NetworkInterface intf = (NetworkInterface) en.nextElement();
        for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
          InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
          if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
            String ipAddress = inetAddress.getHostAddress().toString();
            this.ip = inetAddress;
            f = true;
            break;
          }
        }
        if (f) break;
      }
    } catch (SocketException ex) {
      ex.printStackTrace();
      System.exit(1);
    }
    this.teams = new HashMap<String, Team>();
    this.judges = new HashMap<String, Judge>();
    this.problems = new HashMap<String, ProblemInfo>();
    this.scheduler = new Scheduler();
    this.timer = new ContestTimer(300 * 60);

    try {
      readConfigure();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      System.exit(1);
    }
    this.scoreBoardHttpServer = new ScoreBoardHttpServer(this.scoreBoardPort);
  }
Ejemplo n.º 26
0
  /**
   * Name: getIPAddress Description: Iterates through the device's IPAddresses and returns first
   * non-local IPAddress
   *
   * @return String containing the first non-local IPAddress of the device.
   */
  public InetAddress getIPAddress() {

    try {
      for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
          en.hasMoreElements(); ) {

        NetworkInterface networkInterface = en.nextElement();

        for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses();
            enumIpAddr.hasMoreElements(); ) {

          InetAddress inetAddress = enumIpAddr.nextElement();

          if (!inetAddress.isLoopbackAddress()
              && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
            return inetAddress;
          }
        }
      }
      return InetAddress.getByName("127.0.0.1");

    } catch (SocketException ex) {
      ex.printStackTrace();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
    return null;
  }
Ejemplo n.º 27
0
  public static String getLocalAddress() {
    try {
      // 遍历网卡,查找一个非回路ip地址并返回
      Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
      InetAddress ipv6Address = null;
      while (enumeration.hasMoreElements()) {
        final NetworkInterface networkInterface = enumeration.nextElement();
        final Enumeration<InetAddress> en = networkInterface.getInetAddresses();
        while (en.hasMoreElements()) {
          final InetAddress address = en.nextElement();
          if (!address.isLoopbackAddress()) {
            if (address instanceof Inet6Address) {
              ipv6Address = address;
            } else {
              // 优先使用ipv4
              return normalizeHostAddress(address);
            }
          }
        }
      }
      // 没有ipv4,再使用ipv6
      if (ipv6Address != null) {
        return normalizeHostAddress(ipv6Address);
      }
      final InetAddress localHost = InetAddress.getLocalHost();
      return normalizeHostAddress(localHost);
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }

    return null;
  }
Ejemplo n.º 28
0
 /**
  * 获取本地Ip地址
  *
  * @param context
  * @return
  */
 public static String getLocalIpAddress(Context context) {
   WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
   if (wifiInfo != null && wifiInfo.getIpAddress() != 0) {
     return android.text.format.Formatter.formatIpAddress(wifiInfo.getIpAddress());
   } else {
     try {
       Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
       while (en.hasMoreElements()) {
         NetworkInterface intf = en.nextElement();
         Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
         while (enumIpAddr.hasMoreElements()) {
           InetAddress inetAddress = enumIpAddr.nextElement();
           if (!inetAddress.isLoopbackAddress()
               && inetAddress.getHostAddress().indexOf(":") == -1) {
             String ipAddress = inetAddress.getHostAddress();
             if (!TextUtils.isEmpty(ipAddress) && !ipAddress.contains(":")) {
               return ipAddress;
             }
           }
         }
       }
     } catch (SocketException e) {
       e.printStackTrace();
     }
   }
   return null;
 }
Ejemplo n.º 29
0
    @Override
    public void run() {
      Log.d(TAG, "Starting keep alive...");
      DatagramSocket socket = null;
      try {
        socket = new DatagramSocket(PORT);
        try {
          InetAddress host = InetAddress.getByName(mAddress);
          while (mTransmit) {
            byte[] buffer = {0x66};
            DatagramPacket out = new DatagramPacket(buffer, buffer.length, host, PORT);
            socket.send(out);
            sleep(mInterval);
          }
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }

      } catch (SocketException e) {
        e.printStackTrace();
      } finally {
        if (socket != null) {
          socket.close();
        }
      }
    }
Ejemplo n.º 30
0
  @Override
  protected void launchNewThread() throws IOException {
    final Socket socket;
    try {
      socket = server.accept();
    } catch (SocketException e) {
      if (e.getMessage().equals("socket closed")) {
        return;
      }
      throw e;
    }
    try {
      JLSTConnection client = new JLSTConnection(socket);
      client.writeUnencryptedObject(crypto.getPublicKey());

      DataPackage data = (DataPackage) client.readUnencryptedObject();

      SecretKey key = new SecretKeySpec(crypto.decrypt((byte[]) data.getObjects()[0]), "AES");
      client.getAESSecurityService().setPublicKey(key);
      client.getAESSecurityService().setPrivateKey(key);

      client
          .getAESSecurityService()
          .setParameters(new IvParameterSpec(crypto.decrypt((byte[]) data.getObjects()[1])));

      ClientData event = new ClientData(client);
      launchThreadForConnectedClient(event, "JLSTServer");
    } catch (CryptographyException | ClassNotFoundException e) {
      launchNewThread();
      throw new IOException(e);
    }
  }