public static boolean isReachable(InetAddress localInetAddr, InetAddress remoteInetAddr,int port, int timeout) { 
		
		boolean isReachable = false; 
		Socket socket = null; 
		try{ 
		 socket = new Socket(); 
		 // 端口号设置为 0 表示在本地挑选一个可用端口进行连接
		 SocketAddress localSocketAddr = new InetSocketAddress(localInetAddr, 0); 
		 socket.bind(localSocketAddr); 
		 InetSocketAddress endpointSocketAddr = new InetSocketAddress(remoteInetAddr, port); 
		 socket.connect(endpointSocketAddr, timeout);        
		 System.out.println("SUCCESS - connection established! Local: " + 
				 			localInetAddr.getHostAddress() + " remote: " + 
				 			remoteInetAddr.getHostAddress() + " port" + port); 
		 isReachable = true; 
		} catch(IOException e) { 
		 System.out.println("FAILRE - CAN not connect! Local: " + 
				 	localInetAddr.getHostAddress() + " remote: " + 
				 	remoteInetAddr.getHostAddress() + " port" + port); 
		} finally{ 
		 if(socket != null) { 
		 try{ 
		 socket.close(); 
		 } catch(IOException e) { 
		    System.out.println("Error occurred while closing socket.."); 
		   } 
		 } 
		} 
		return isReachable; 
	}
예제 #2
0
  /**
   * Add a standardised amount of information about an interface. This is in the form:
   *
   * <pre>
   *     [interfaces]
   *       |
   *       |
   *       +--[ id ] (branch)
   *       |   |
   *       |   +-- "order"  (integer metric: 1 .. 2 ..)
   *       |   +-- "FQDN" (string metric: the host's FQDN, as presented by the door)
   *       |   +-- "address" (string metric: the host's address; e.g., "127.0.0.1")
   *       |   +-- "address-type"    (string metric: "IPv4", "IPv6" or "unknown")
   *       |   +-- "scope"    (string metric: "IPv4", "IPv6" or "unknown")
   *       |
   * </pre>
   *
   * @param update The StateUpdate to append the new metrics.
   * @param parentPath the path that the id branch will be added.
   * @param lifetime how long the created metrics should last.
   */
  private void addInterfaceInfo(
      StateUpdate update, StatePath parentPath, InetAddress address, long lifetime) {
    StatePath pathToInterfaceBranch = parentPath.newChild(address.getHostAddress());

    String hostName = address.getHostName();
    update.appendUpdate(
        pathToInterfaceBranch.newChild("FQDN"), new StringStateValue(hostName, lifetime));

    String urlName = (isInetAddress(hostName)) ? toUriString(address) : hostName;
    update.appendUpdate(
        pathToInterfaceBranch.newChild("url-name"), new StringStateValue(urlName, lifetime));

    update.appendUpdate(
        pathToInterfaceBranch.newChild("address"),
        new StringStateValue(address.getHostAddress(), lifetime));
    update.appendUpdate(
        pathToInterfaceBranch.newChild("address-type"),
        new StringStateValue(
            (address instanceof Inet4Address)
                ? "IPv4"
                : (address instanceof Inet6Address) ? "IPv6" : "unknown",
            lifetime));
    update.appendUpdate(
        pathToInterfaceBranch.newChild("scope"),
        new StringStateValue(NetworkUtils.InetAddressScope.of(address).toString().toLowerCase()));
  }
예제 #3
0
 public static String normalizeHostAddress(final InetAddress localHost) {
   if (localHost instanceof Inet6Address) {
     return "[" + localHost.getHostAddress() + "]";
   } else {
     return localHost.getHostAddress();
   }
 }
예제 #4
0
 /**
  * Returns a hash that should be consistent for any individual swarm client (as long as it has a
  * persistent IP) and should be unique to that client.
  *
  * @param remoteFsRoot the file system root should be part of the hash (to support multiple swarm
  *     clients from the same machine)
  * @return our best effort at a consistent hash
  */
 public static String hash(File remoteFsRoot) {
   StringBuilder buf = new StringBuilder();
   try {
     buf.append(remoteFsRoot.getCanonicalPath()).append('\n');
   } catch (IOException e) {
     buf.append(remoteFsRoot.getAbsolutePath()).append('\n');
   }
   try {
     for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {
       for (InetAddress ia : Collections.list(ni.getInetAddresses())) {
         if (ia instanceof Inet4Address) {
           buf.append(ia.getHostAddress()).append('\n');
         } else if (ia instanceof Inet6Address) {
           buf.append(ia.getHostAddress()).append('\n');
         }
       }
       byte[] hardwareAddress = ni.getHardwareAddress();
       if (hardwareAddress != null) {
         buf.append(Arrays.toString(hardwareAddress));
       }
     }
   } catch (SocketException e) {
     // oh well we tried
   }
   return DigestUtils.md5Hex(buf.toString()).substring(0, 8);
 }
예제 #5
0
  private static void parseTCPMsg(byte[] msg) throws UnknownHostException {
    switch (msg[0]) {
      case 0x00:
        if (msg[1] == 0x01) System.out.println("Server: OPEN");
        else System.out.println("Server: CLOSED");
        break;
      case 0x01:
        if (msg[1] == 0x00)
          System.out.printf("[ERR]: %s", new String(Arrays.copyOfRange(msg, 2, msg.length)));
        else {
          ByteBuffer buffer = ByteBuffer.wrap(Arrays.copyOfRange(msg, 1, msg.length));
          userId = new UUID(buffer.getLong(), buffer.getLong());
          groupIp =
              InetAddress.getByAddress(ByteBuffer.allocate(4).putInt(buffer.getInt()).array());

          // connect to the group and start receiving
          udpSocket.connect(groupIp.getHostAddress());
          udpSocket.startReceive(new UDPHandler());

          System.out.printf(
              "User ID: %s\nGroup IP: %s\nPort: %d\n",
              userId.toString(), groupIp.getHostAddress(), buffer.getInt());
        }
        break;
      case 0x02:
        if (msg[1] == 0x00)
          System.out.printf("[ERR]: %s", new String(Arrays.copyOfRange(msg, 2, msg.length)));
        else System.out.println("Successfully deregestered");
      default:
        System.out.println("[ERR] Inavlid msg");
    }
  }
예제 #6
0
 public static boolean validateProxy(HttpHost p) {
   if (localAddr == null) {
     logger.error("cannot get local IP");
     return false;
   }
   boolean isReachable = false;
   Socket socket = null;
   try {
     socket = new Socket();
     socket.bind(new InetSocketAddress(localAddr, 0));
     InetSocketAddress endpointSocketAddr =
         new InetSocketAddress(p.getAddress().getHostAddress(), p.getPort());
     socket.connect(endpointSocketAddr, 3000);
     logger.debug(
         "SUCCESS - connection established! Local: "
             + localAddr.getHostAddress()
             + " remote: "
             + p);
     isReachable = true;
   } catch (IOException e) {
     logger.warn(
         "FAILRE - CAN not connect! Local: " + localAddr.getHostAddress() + " remote: " + p);
   } finally {
     if (socket != null) {
       try {
         socket.close();
       } catch (IOException e) {
         logger.warn("Error occurred while closing socket of validating proxy", e);
       }
     }
   }
   return isReachable;
 }
예제 #7
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();
    }
  }
예제 #8
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();
    }
  }
  @Test
  public void testThatBindingOnDifferentHostsWorks() throws Exception {
    int[] ports = getRandomPorts(2);
    InetAddress firstNonLoopbackAddress =
        NetworkUtils.getFirstNonLoopbackAddress(NetworkUtils.StackType.IPv4);
    assumeTrue(
        "No IP-v4 non-loopback address available - are you on a plane?",
        firstNonLoopbackAddress != null);
    Settings settings =
        settingsBuilder()
            .put("network.host", "127.0.0.1")
            .put("transport.tcp.port", ports[0])
            .put("transport.profiles.default.bind_host", "127.0.0.1")
            .put("transport.profiles.client1.bind_host", firstNonLoopbackAddress.getHostAddress())
            .put("transport.profiles.client1.port", ports[1])
            .build();

    ThreadPool threadPool = new ThreadPool("tst");
    try (NettyTransport ignored = startNettyTransport(settings, threadPool)) {
      assertPortIsBound("127.0.0.1", ports[0]);
      assertPortIsBound(firstNonLoopbackAddress.getHostAddress(), ports[1]);
      assertConnectionRefused(ports[1]);
    } finally {
      terminate(threadPool);
    }
  }
예제 #10
0
  private static void connectAndPlay(VideoComponent vc, String settings, String addr)
      throws UnknownHostException, IOException {
    // find this ip
    updateResource();

    Socket skt = null;
    if (addr.length() > 0) {
      Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
      while (e.hasMoreElements()) {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        Enumeration<InetAddress> ee = n.getInetAddresses();
        while (ee.hasMoreElements()) {
          InetAddress i = (InetAddress) ee.nextElement();
          if (!i.isLinkLocalAddress() && !i.isLoopbackAddress()) {
            pushLog("CLNT START IP:" + i.getHostAddress());
            clientLoc = i.getHostAddress();
          }
        }
      }
      serverLoc = addr;
      skt = new Socket(serverLoc, 45000);
    } else if (addr.length() == 0) {
      clientLoc = "127.0.0.1";
      serverLoc = "127.0.0.1";
      skt = new Socket("localhost", 45000);
    }

    skt.setReuseAddress(true);
    BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
    out = new PrintWriter(skt.getOutputStream(), true);

    JSONObject portNeg = new JSONObject(in.readLine());
    int port = portNeg.getInt("port");
    System.out.println("Client port: " + port);

    JSONObject json_settings = new JSONObject();
    json_settings.put("settings", attribute + " " + clientbw + " " + request);
    out.println(json_settings.toString());

    pushLog("> SYS: CNCT SUCCESS");
    startStreaming(vc, settings, port);

    pushLog("> CTRL: LISTENING FOR COMMANDS");
    Scanner s = new Scanner(System.in);
    String line;
    JSONObject json_command;
    while (true) {
      line = s.nextLine();
      json_command = new JSONObject();
      json_command.put("command", line);
      // json_command.put("bandwidth", "");
      out.println(json_command.toString());

      if (line.equals("stop")) break;
    }

    in.close();
    out.close();
    skt.close();
  }
예제 #11
0
 /**
  * 根据网卡取本机配置的IP 如果是双网卡的,则取出外网IP
  *
  * @return
  */
 public static String getNetIp() {
   String localip = null; // 本地IP,如果没有配置外网IP则返回它
   String netip = null; // 外网IP
   try {
     Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
     InetAddress ip = null;
     boolean finded = false; // 是否找到外网IP
     while (netInterfaces.hasMoreElements() && !finded) {
       NetworkInterface ni = netInterfaces.nextElement();
       Enumeration<InetAddress> address = ni.getInetAddresses();
       while (address.hasMoreElements()) {
         ip = address.nextElement();
         if (!ip.isSiteLocalAddress()
             && !ip.isLoopbackAddress()
             && ip.getHostAddress().indexOf(":") == -1) { // 外网IP
           netip = ip.getHostAddress();
           finded = true;
           break;
         } else if (ip.isSiteLocalAddress()
             && !ip.isLoopbackAddress()
             && ip.getHostAddress().indexOf(":") == -1) { // 内网IP
           localip = ip.getHostAddress();
         }
       }
     }
   } catch (SocketException e) {
     logger.error(e);
   }
   if (netip != null && !"".equals(netip)) {
     return netip;
   } else {
     return localip;
   }
 }
예제 #12
0
  public static String getLocalIpAddress2() {
    String networkIp = null;
    try {
      List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
      for (NetworkInterface iface : interfaces) {
        if (iface.getDisplayName().equals("eth0")) {
          List<InetAddress> addresses = Collections.list(iface.getInetAddresses());
          for (InetAddress address : addresses) {
            if (address instanceof Inet4Address) {
              networkIp = address.getHostAddress();
            }
          }
        } else if (iface.getDisplayName().equals("wlan0")) {
          List<InetAddress> addresses = Collections.list(iface.getInetAddresses());
          for (InetAddress address : addresses) {
            if (address instanceof Inet4Address) {
              networkIp = address.getHostAddress();
            }
          }
        }
      }
    } catch (SocketException e) {
      e.printStackTrace();
    }

    return networkIp;
  }
예제 #13
0
 private static DhcpV4Message handleMessage1(InetAddress localAddress, DhcpV4Message dhcpMessage) {
   InetAddress linkAddress;
   if (dhcpMessage.getGiAddr().equals(DhcpConstants.ZEROADDR_V4)) {
     linkAddress = localAddress;
     if (log.isInfoEnabled()) {
       log.info(
           "Handling client request on local client link address: {}",
           linkAddress.getHostAddress());
     }
   } else {
     linkAddress = dhcpMessage.getGiAddr();
     if (log.isInfoEnabled()) {
       log.info(
           "Handling client request on remote client link address: {}",
           linkAddress.getHostAddress());
     }
   }
   DhcpV4MsgTypeOption msgTypeOption =
       (DhcpV4MsgTypeOption) dhcpMessage.getDhcpOption(DhcpConstants.V4OPTION_MESSAGE_TYPE);
   DhcpV4Message result;
   if (msgTypeOption != null) {
     result = handleMessage2(dhcpMessage, linkAddress, msgTypeOption);
   } else {
     log.error("No message type option found in request.");
     result = null;
   }
   return result;
 }
예제 #14
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;
 }
예제 #15
0
파일: ArpPacket.java 프로젝트: sjroot/lab
 @Override
 public String toString() {
   if (isRequest())
     return String.format(
         "Who has %s? Tell %s", targetIp.getHostAddress(), senderIp.getHostAddress());
   else return String.format("%s is at %s", senderIp.getHostAddress(), senderMac);
 }
예제 #16
0
 public static String getFirstNonLocalhostIp() {
   Map<InetAddress, String> inetAddressMap = getInetAddressMap();
   for (InetAddress inetAddress : inetAddressMap.keySet()) {
     if (!inetAddress.isLoopbackAddress() && !(inetAddress.getHostAddress().indexOf(":") > -1)) {
       return inetAddress.getHostAddress();
     }
   }
   return null;
 }
예제 #17
0
 public static String getFirstNonWifiIp() {
   Map<InetAddress, String> inetAddressMap = getInetAddressMap();
   for (InetAddress inetAddress : inetAddressMap.keySet()) {
     if (!inetAddress.isLoopbackAddress()
         && !(inetAddress.getHostAddress().indexOf(":") > -1)
         && !inetAddressMap.get(inetAddress).startsWith("wlan")) {
       return inetAddress.getHostAddress();
     }
   }
   return null;
 }
예제 #18
0
  /**
   * Finds all the hosts which are on the same subnet as the finder Author: David WORKS ONLY FOR
   * MASKS OF 8
   *
   * @param list is the listview which will receive all the ip's of available games
   */
  public void findGames(ObservableList list) {
    // Get network interfaces
    Enumeration<NetworkInterface> networkInterfaces = null;
    try {
      networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
      e.printStackTrace();
    }

    // Loop through network interfaces
    while (networkInterfaces.hasMoreElements()) {
      NetworkInterface networkInterface = networkInterfaces.nextElement();

      Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();

      // Loop through interface addresses
      while (inetAddresses.hasMoreElements()) {
        InetAddress address = inetAddresses.nextElement();

        // If adress is IPv6 we skip
        if (address instanceof Inet6Address) continue;

        String localHost;
        localHost = address.getHostAddress();

        // Prepare for subnetting
        String[] nibbles = localHost.split("/")[0].split("\\.");

        localHost = String.format("%s.%s.%s", nibbles[0], nibbles[1], nibbles[2]);

        if (nibbles[0].equals("127")) continue;

        // Loop through all local subips
        for (int i = 1; i <= 255; i++) {
          String host = String.format("%s.%s", localHost, i);

          // Prepare funtion to execute
          pool.execute(
              () -> {
                SocketAddress sockaddr = new InetSocketAddress(host, 8085);
                Socket socket = new Socket();
                try {
                  socket.connect(sockaddr, TIMEOUT);

                  // If we're not finding our localhost it should be fine
                  if (!host.equals(address.getHostAddress().split("/"))) list.add(host);
                } catch (IOException ex) {
                  ex.printStackTrace();
                }
              });
        }
      }
    }
  }
 public String getLocalAddress() {
   InetAddress mcastAddr = ssdpMultiGroup.getAddress();
   Enumeration addrs = ssdpMultiIf.getInetAddresses();
   while (addrs.hasMoreElements()) {
     InetAddress addr = (InetAddress) addrs.nextElement();
     if (mcastAddr instanceof Inet6Address && addr instanceof Inet6Address)
       return addr.getHostAddress();
     if (mcastAddr instanceof Inet4Address && addr instanceof Inet4Address)
       return addr.getHostAddress();
   }
   return "";
 }
예제 #20
0
 @Override
 public String toString() {
   InetAddress address = getConnection().getInetAddress();
   if (getState() == LoginClientState.AUTHED_LOGIN) {
     return "["
         + getAccount()
         + " ("
         + (address == null ? "disconnected" : address.getHostAddress())
         + ")]";
   }
   return "[" + (address == null ? "disconnected" : address.getHostAddress()) + "]";
 }
예제 #21
0
  /** Sets the local IP address into the variable <i>localIpAddress</i> */
  public static void setLocalIpAddress() {
    localIpAddress = "127.0.0.1";

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

        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
            enumIpAddr.hasMoreElements(); ) {
          InetAddress inetAddress = enumIpAddr.nextElement();

          if (!inetAddress.isLoopbackAddress()) {
            if (inetAddress.getHostAddress().toString().contains(":")) continue;
            if (!PreferenceManager.getDefaultSharedPreferences(getUIContext())
                .getBoolean(Settings.PREF_STUN, Settings.DEFAULT_STUN)) {
              localIpAddress = inetAddress.getHostAddress().toString();
            } else {
              try {
                String StunServer =
                    PreferenceManager.getDefaultSharedPreferences(getUIContext())
                        .getString(Settings.PREF_STUN_SERVER, Settings.DEFAULT_STUN_SERVER);
                int StunServerPort =
                    Integer.valueOf(
                        PreferenceManager.getDefaultSharedPreferences(getUIContext())
                            .getString(
                                Settings.PREF_STUN_SERVER_PORT, Settings.DEFAULT_STUN_SERVER_PORT));

                DiscoveryTest StunDiscover =
                    new DiscoveryTest(inetAddress, StunServer, StunServerPort);

                // call out to stun server
                StunDiscover.test();
                // System.out.println("Public ip is:" +
                // StunDiscover.di.getPublicIP().getHostAddress());
                localIpAddress = StunDiscover.di.getPublicIP().getHostAddress();
              } catch (BindException be) {
                if (!Sipdroid.release)
                  System.out.println(inetAddress.toString() + ": " + be.getMessage());
              } catch (Exception e) {
                if (!Sipdroid.release) {
                  System.out.println(e.getMessage());
                  e.printStackTrace();
                }
              }
            }
          }
        }
      }
    } catch (Exception ex) {
      // do nothing
    }
  }
  /**
   * Retrieves an array of Strings naming the distinct, known to be valid local InetAddress names
   * for this machine. The process is to collect and return the union of the following sets:
   *
   * <ol>
   *   <li>InetAddress.getAllByName(InetAddress.getLocalHost().getHostAddress())
   *   <li>InetAddress.getAllByName(InetAddress.getLocalHost().getHostName())
   *   <li>InetAddress.getAllByName(InetAddress.getByName(null).getHostAddress())
   *   <li>InetAddress.getAllByName(InetAddress.getByName(null).getHostName())
   *   <li>InetAddress.getByName("loopback").getHostAddress()
   *   <li>InetAddress.getByName("loopback").getHostname()
   * </ol>
   *
   * @return the distinct, known to be valid local InetAddress names for this machine
   */
  public static String[] listLocalInetAddressNames() {

    InetAddress addr;
    InetAddress[] addrs;
    HashSet set;

    set = new HashSet();

    try {
      addr = InetAddress.getLocalHost();
      addrs = InetAddress.getAllByName(addr.getHostAddress());

      for (int i = 0; i < addrs.length; i++) {
        set.add(addrs[i].getHostAddress());
        set.add(addrs[i].getHostName());
      }

      addrs = InetAddress.getAllByName(addr.getHostName());

      for (int i = 0; i < addrs.length; i++) {
        set.add(addrs[i].getHostAddress());
        set.add(addrs[i].getHostName());
      }
    } catch (Exception e) {
    }

    try {
      addr = InetAddress.getByName(null);
      addrs = InetAddress.getAllByName(addr.getHostAddress());

      for (int i = 0; i < addrs.length; i++) {
        set.add(addrs[i].getHostAddress());
        set.add(addrs[i].getHostName());
      }

      addrs = InetAddress.getAllByName(addr.getHostName());

      for (int i = 0; i < addrs.length; i++) {
        set.add(addrs[i].getHostAddress());
        set.add(addrs[i].getHostName());
      }
    } catch (Exception e) {
    }

    try {
      set.add(InetAddress.getByName("loopback").getHostAddress());
      set.add(InetAddress.getByName("loopback").getHostName());
    } catch (Exception e) {
    }

    return (String[]) set.toArray(new String[set.size()]);
  }
예제 #23
0
  public String detectPPP() {
    try {
      List<String> linkPPP = new ArrayList<String>();
      List<String> linkDSL = new ArrayList<String>();
      Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();

      // System.out.println("NETS VALUES"+" "+nets);

      // System.out.println("INITIALY VALUES"+" "+linkPPP);

      for (NetworkInterface netInf : Collections.list(nets)) {
        // System.out.println("netInf VALUES"+" "+netInf);

        if (!netInf.isLoopback()) {
          if (netInf.isPointToPoint()) {
            // System.out.println("in point to point");
            // System.out.println("netInf VALUES"+" "+netInf);
            Enumeration<InetAddress> inetAdd = netInf.getInetAddresses();
            // System.out.println("inetAdd VALUES"+" "+inetAdd);
            for (InetAddress inet : Collections.list(inetAdd)) {
              // System.out.println("inet vales in the ineer loop"+" "+inet);
              // System.out.println("linkPPP vales before add in the ineer loop"+" "+linkPPP);
              linkPPP.add(inet.getHostAddress()); // 				
              // System.out.println("linkPPP vales after add in the ineer loop"+" "+linkPPP);
              // System.out.println("IP:"+" "+inet.getHostAddress());
            }
          } else {
            Enumeration<InetAddress> inetAdd = netInf.getInetAddresses();
            for (InetAddress inet : Collections.list(inetAdd)) {
              linkDSL.add(inet.getHostAddress());
            }
          }
        }
      }
      // System.out.println("FINAL VALUE of linkPPP"+" "+linkPPP.get(0));
      // System.out.println("FINAL VALUES DSL"+" "+linkDSL);
      int i = linkPPP.size();
      if (i != 0) {
        // System.out.println("linkPPP"+" "+linkPPP.get(i-1));
        return linkPPP.get(i - 1) + ",y";
        // return linkPPP.get(0)+",y";
      } else if (linkDSL.size() != 0) return linkDSL.get(i - 1) + ",n";
      // return linkDSL.get(0)+",n";
      else return "127.0.0.1,n";
    } catch (SocketException e) {
      // e.printStackTrace();
      System.err.println("exception in ");
    }

    return "127.0.0.1,n";
  }
예제 #24
0
 private static String getHostAddress(ThreadContext context, InetAddress addr, Boolean reverse) {
   String ret;
   if (reverse == null) {
     ret =
         context.runtime.isDoNotReverseLookupEnabled()
             ? addr.getHostAddress()
             : addr.getCanonicalHostName();
   } else if (reverse) {
     ret = addr.getCanonicalHostName();
   } else {
     ret = addr.getHostAddress();
   }
   return ret;
 }
예제 #25
0
  /**
   * Returns the hostname for this address.
   *
   * <p>If there is a security manager, this method first calls its <code>checkConnect</code> method
   * with the hostname and <code>-1</code> as its arguments to see if the calling code is allowed to
   * know the hostname for this IP address, i.e., to connect to the host. If the operation is not
   * allowed, it will return the textual representation of the IP address.
   *
   * @return the host name for this IP address, or if the operation is not allowed by the security
   *     check, the textual representation of the IP address.
   * @param check make security check if true
   * @see SecurityManager#checkConnect
   */
  private static String getHostFromNameService(InetAddress addr, boolean check) {
    String host = null;
    for (NameService nameService : nameServices) {
      try {
        // first lookup the hostname
        host = nameService.getHostByAddr(addr.getAddress());

        /* check to see if calling code is allowed to know
         * the hostname for this IP address, ie, connect to the host
         */
        if (check) {
          SecurityManager sec = System.getSecurityManager();
          if (sec != null) {
            sec.checkConnect(host, -1);
          }
        }

        /* now get all the IP addresses for this hostname,
         * and make sure one of them matches the original IP
         * address. We do this to try and prevent spoofing.
         */

        InetAddress[] arr = InetAddress.getAllByName0(host, check);
        boolean ok = false;

        if (arr != null) {
          for (int i = 0; !ok && i < arr.length; i++) {
            ok = addr.equals(arr[i]);
          }
        }

        // XXX: if it looks a spoof just return the address?
        if (!ok) {
          host = addr.getHostAddress();
          return host;
        }

        break;

      } catch (SecurityException e) {
        host = addr.getHostAddress();
        break;
      } catch (UnknownHostException e) {
        host = addr.getHostAddress();
        // let next provider resolve the hostname
      }
    }

    return host;
  }
예제 #26
0
  private List<String> getServerInterfaces() {

    List<String> bindInterfaces = new ArrayList<String>();

    String interfaceName = JiveGlobals.getXMLProperty("network.interface");
    String bindInterface = null;
    if (interfaceName != null) {
      if (interfaceName.trim().length() > 0) {
        bindInterface = interfaceName;
      }
    }

    int adminPort = JiveGlobals.getXMLProperty("adminConsole.port", 9090);
    int adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091);

    if (bindInterface == null) {
      try {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netInterface : Collections.list(nets)) {
          Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
          for (InetAddress address : Collections.list(addresses)) {
            if ("127.0.0.1".equals(address.getHostAddress())) {
              continue;
            }
            if (address.getHostAddress().startsWith("0.")) {
              continue;
            }
            Socket socket = new Socket();
            InetSocketAddress remoteAddress =
                new InetSocketAddress(address, adminPort > 0 ? adminPort : adminSecurePort);
            try {
              socket.connect(remoteAddress);
              bindInterfaces.add(address.getHostAddress());
              break;
            } catch (IOException e) {
              // Ignore this address. Let's hope there is more addresses to validate
            }
          }
        }
      } catch (SocketException e) {
        // We failed to discover a valid IP address where the admin console is running
        return null;
      }
    } else {
      bindInterfaces.add(bindInterface);
    }

    return bindInterfaces;
  }
예제 #27
0
 /**
  * @param address IP address to bind
  * @param dns JmDNS instance
  * @param jmdnsName JmDNS name
  * @return new HostInfo
  */
 public static HostInfo newHostInfo(InetAddress address, JmDNSImpl dns, String jmdnsName) {
   HostInfo localhost = null;
   String aName = "";
   InetAddress addr = address;
   try {
     if (addr == null) {
       String ip = System.getProperty("net.mdns.interface");
       if (ip != null) {
         addr = InetAddress.getByName(ip);
       } else {
         addr = InetAddress.getLocalHost();
         if (addr.isLoopbackAddress()) {
           // Find local address that isn't a loopback address
           InetAddress[] addresses =
               NetworkTopologyDiscovery.Factory.getInstance().getInetAddresses();
           if (addresses.length > 0) {
             addr = addresses[0];
           }
         }
       }
       aName = addr.getHostName();
       if (addr.isLoopbackAddress()) {
         logger.warning("Could not find any address beside the loopback.");
       }
     } else {
       aName = addr.getHostName();
     }
     if (aName.contains("in-addr.arpa") || (aName.equals(addr.getHostAddress()))) {
       aName =
           ((jmdnsName != null) && (jmdnsName.length() > 0) ? jmdnsName : addr.getHostAddress());
     }
   } catch (final IOException e) {
     logger.log(
         Level.WARNING,
         "Could not intialize the host network interface on "
             + address
             + "because of an error: "
             + e.getMessage(),
         e);
     // This is only used for running unit test on Debian / Ubuntu
     addr = loopbackAddress();
     aName = ((jmdnsName != null) && (jmdnsName.length() > 0) ? jmdnsName : "computer");
   }
   // A host name with "." is illegal. so strip off everything and append .local.
   aName = aName.replace('.', '-');
   aName += ".local.";
   localhost = new HostInfo(addr, aName, dns);
   return localhost;
 }
예제 #28
0
 public static boolean isServer() throws Exception {
   boolean isServer = false;
   InetAddress IP = InetAddress.getLocalHost();
   try {
     if (IP.getHostAddress().toString().equals("54.186.249.201")
         || IP.getHostAddress().toString().equals("172.31.40.246")
         || IP.getHostAddress().toString().equals("128.199.237.142")
         || IP.getHostAddress().toString().equals("saracourierservice.tk")) {
       isServer = true;
     }
   } catch (Exception ex) {
     throw ex;
   }
   return isServer;
 }
예제 #29
0
 @Override
 public boolean isEqual(String checkURI) throws CommunicationException {
   try {
     RMIAddress checkAddr = new RMIAddress(checkURI);
     InetAddress checkHost = InetAddress.getByName(checkAddr.host);
     checkURI =
         String.format(
             "rmi://%s:%d/%s", checkHost.getHostAddress(), checkAddr.port, checkAddr.remoteID);
     InetAddress thisHost = InetAddress.getByName(checkAddr.host);
     String thisURI = String.format("rmi://%s:%d/%s", thisHost.getHostAddress(), port, remoteID);
     return thisURI.equalsIgnoreCase(checkURI);
   } catch (UnknownHostException e) {
     throw new CommunicationException(e);
   }
 }
예제 #30
0
 private void setupProxy(
     ConnectivitySettings cs, int connectionType, InetSocketAddress inetSocketAddress) {
   cs.setConnectionType(connectionType);
   InetAddress address = inetSocketAddress.getAddress();
   cs.setProxyHost((address != null) ? address.getHostAddress() : inetSocketAddress.getHostName());
   cs.setProxyPort(inetSocketAddress.getPort());
 }