Java Code Examples for java.net.UnknownHostException

The following are top voted examples for showing how to use java.net.UnknownHostException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdk8u-jdk   File: SnmpEngineImpl.java   Source Code and License 7 votes vote down vote up
/**
 * Constructor. A Local Configuration Datastore is passed to the engine. It will be used to store and retrieve data (engine Id, engine boots).
 * <P> WARNING : The SnmpEngineId is computed as follow:
 * <ul>
 * <li> If an lcd file is provided containing the property "localEngineID", this property value is used.</li>.
 * <li> If not, if the passed engineID is not null, this engine ID is used.</li>
 * <li> If not, a time based engineID is computed.</li>
 * </ul>
 * This constructor should be called by an <CODE>SnmpEngineFactory</CODE>. Don't call it directly.
 * @param fact The factory used to instantiate this engine.
 * @param lcd The local configuration datastore.
 * @param engineid The engine ID to use. If null is provided, an SnmpEngineId is computed using the current time.
 * @throws UnknownHostException Exception thrown, if the host name located in the property "localEngineID" is invalid.
 */
public SnmpEngineImpl(SnmpEngineFactory fact,
                      SnmpLcd lcd,
                      SnmpEngineId engineid) throws UnknownHostException {

    init(lcd, fact);
    initEngineID();
    if(this.engineid == null) {
        if(engineid != null)
            this.engineid = engineid;
        else
            this.engineid = SnmpEngineId.createEngineId();
    }
    lcd.storeEngineId(this.engineid);
    if (SNMP_LOGGER.isLoggable(Level.FINER)) {
        SNMP_LOGGER.logp(Level.FINER, SnmpEngineImpl.class.getName(),
                "SnmpEngineImpl(SnmpEngineFactory,SnmpLcd,SnmpEngineId)",
                "LOCAL ENGINE ID: " + this.engineid);
    }
}
 
Example 2
Project: uDetective   File: ElasticSearchDataSource.java   Source Code and License 7 votes vote down vote up
@Override
public TransportClient connect() {
    Settings settings = Settings.builder()
        .put("cluster.name", "elasticsearch")
        .put("client.transport.sniff", true).build();       
    
    try {
        client = new PreBuiltTransportClient(settings)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("event-apptst01.as.it.ubc.ca"), 9300))
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("event-apptst02.as.it.ubc.ca"), 9300));        
    } catch (UnknownHostException uhe) {
        logger.error(uhe.toString());
    }
    
    return client;
}
 
Example 3
Project: BedrockProxy   File: OpenConnectionResponseTwo.java   Source Code and License 7 votes vote down vote up
@Override
public void decode() {
    try {
        this.magic = this.checkMagic();
        this.serverGuid = this.readLong();
        this.clientAddress = this.readAddress();
        this.maximumTransferUnit = this.readUShort();
        this.encryptionEnabled = this.readBoolean();
    } catch (UnknownHostException e) {
        this.failed = true;
        this.magic = false;
        this.serverGuid = 0;
        this.clientAddress = null;
        this.maximumTransferUnit = 0;
        this.encryptionEnabled = false;
        this.clear();
    }
}
 
Example 4
Project: java-coap   File: ServerIntegrationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void requestWithAccept() throws UnknownHostException, IOException, InterruptedException, Exception {
    CoapServer cnn = CoapServerBuilder.newBuilder().transport(0).build();
    cnn.start();

    CoapPacket request = new CoapPacket(new InetSocketAddress("127.0.0.1", SERVER_PORT));
    request.setMethod(Method.GET);
    request.headers().setUriPath("/test2");
    request.setMessageId(1647);

    short[] acceptList = {MediaTypes.CT_APPLICATION_JSON};
    request.headers().setAccept(acceptList);

    assertEquals(Code.C406_NOT_ACCEPTABLE, cnn.makeRequest(request).get().getCode());
    cnn.stop();
}
 
Example 5
Project: https-github.com-apache-zookeeper   File: StaticHostProviderTest.java   Source Code and License 6 votes vote down vote up
private Collection<InetSocketAddress> getServerAddresses(byte size)   {
    if (precomputedLists.containsKey(size)) return precomputedLists.get(size);
    ArrayList<InetSocketAddress> list = new ArrayList<InetSocketAddress>(
            size);
    while (size > 0) {
        try {
            list.add(new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 10, 10, size}), 1234 + size));
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        --size;
    }
    precomputedLists.put(size, list);
    return list;
}
 
Example 6
Project: virtualview_tools   File: Log.java   Source Code and License 6 votes vote down vote up
/**
 * Handy function to get a loggable stack trace from a Throwable
 * @param tr An exception to log
 */
public static String getStackTraceString(Throwable tr) {
    if (tr == null) {
        return "";
    }

    // This is to reduce the amount of log spew that apps do in the non-error
    // condition of the network being unavailable.
    Throwable t = tr;
    while (t != null) {
        if (t instanceof UnknownHostException) {
            return "";
        }
        t = t.getCause();
    }

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    tr.printStackTrace(pw);
    pw.flush();
    return sw.toString();
}
 
Example 7
Project: athena   File: OspfInterfaceImplTest.java   Source Code and License 6 votes vote down vote up
/**
 * Utility for test method.
 */
private OspfInterfaceImpl createOspfInterface1() throws UnknownHostException {
    ospfInterface = new OspfInterfaceImpl();
    OspfAreaImpl ospfArea = new OspfAreaImpl();
    OspfInterfaceChannelHandler ospfInterfaceChannelHandler = EasyMock.createMock(
            OspfInterfaceChannelHandler.class);
    ospfNbr = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("10.226.165.164"),
                              Ip4Address.valueOf("1.1.1.1"), 2,
                              topologyForDeviceAndLink);
    ospfNbr.setState(OspfNeighborState.FULL);
    ospfNbr.setNeighborId(Ip4Address.valueOf("10.226.165.100"));
    ospfInterface = new OspfInterfaceImpl();
    ospfInterface.setIpAddress(Ip4Address.valueOf("10.226.165.164"));
    ospfInterface.setIpNetworkMask(Ip4Address.valueOf("255.255.255.255"));
    ospfInterface.setBdr(Ip4Address.valueOf("111.111.111.111"));
    ospfInterface.setDr(Ip4Address.valueOf("111.111.111.111"));
    ospfInterface.setHelloIntervalTime(20);
    ospfInterface.setInterfaceType(2);
    ospfInterface.setReTransmitInterval(2000);
    ospfInterface.setMtu(6500);
    ospfInterface.setRouterDeadIntervalTime(1000);
    ospfInterface.setRouterPriority(1);
    ospfInterface.setInterfaceType(1);
    ospfInterface.addNeighbouringRouter(ospfNbr);
    return ospfInterface;
}
 
Example 8
Project: MVVMArms   File: ResponseErrorListenerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void handleResponseError(Context context, Throwable t) {
    //用来提供处理所有错误的监听
    //rxjava必要要使用ErrorHandleSubscriber(默认实现Subscriber的onError方法),此监听才生效
    Timber.tag("Catch-Error").w(t.getMessage());
    //这里不光是只能打印错误,还可以根据不同的错误作出不同的逻辑处理
    String msg = "未知错误";
    if (t instanceof UnknownHostException) {
        msg = "网络不可用";
    } else if (t instanceof SocketTimeoutException) {
        msg = "请求网络超时";
    } else if (t instanceof HttpException) {
        HttpException httpException = (HttpException) t;
        msg = convertStatusCode(httpException);
    } else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException) {
        msg = "数据解析错误";
    }
    UiUtils.snackbarText(msg);
}
 
Example 9
Project: hadoop-oss   File: SecurityUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieve the name of the current host. Multihomed hosts may restrict the
 * hostname lookup to a specific interface and nameserver with {@link
 * org.apache.hadoop.fs.CommonConfigurationKeysPublic#HADOOP_SECURITY_DNS_INTERFACE_KEY}
 * and {@link org.apache.hadoop.fs.CommonConfigurationKeysPublic#HADOOP_SECURITY_DNS_NAMESERVER_KEY}
 *
 * @param conf Configuration object. May be null.
 * @return
 * @throws UnknownHostException
 */
static String getLocalHostName(@Nullable Configuration conf)
    throws UnknownHostException {
  if (conf != null) {
    String dnsInterface = conf.get(HADOOP_SECURITY_DNS_INTERFACE_KEY);
    String nameServer = conf.get(HADOOP_SECURITY_DNS_NAMESERVER_KEY);

    if (dnsInterface != null) {
      return DNS.getDefaultHost(dnsInterface, nameServer, true);
    } else if (nameServer != null) {
      throw new IllegalArgumentException(HADOOP_SECURITY_DNS_NAMESERVER_KEY +
          " requires " + HADOOP_SECURITY_DNS_INTERFACE_KEY + ". Check your" +
          "configuration.");
    }
  }

  // Fallback to querying the default hostname as we did before.
  return InetAddress.getLocalHost().getCanonicalHostName();
}
 
Example 10
Project: rskj   File: PeerScoringManagerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void recordEventUsingNodeIDAndAddress() throws UnknownHostException {
    NodeID id = generateNodeID();
    InetAddress address = generateIPAddressV4();

    PeerScoringManager manager = createPeerScoringManager();

    manager.recordEvent(id, address, EventType.INVALID_BLOCK);

    PeerScoring result = manager.getPeerScoring(id);

    Assert.assertNotNull(result);
    Assert.assertFalse(result.isEmpty());
    Assert.assertEquals(1, result.getEventCounter(EventType.INVALID_BLOCK));
    Assert.assertEquals(1, result.getTotalEventCounter());

    result = manager.getPeerScoring(address);

    Assert.assertNotNull(result);
    Assert.assertFalse(result.isEmpty());
    Assert.assertEquals(1, result.getEventCounter(EventType.INVALID_BLOCK));
    Assert.assertEquals(1, result.getTotalEventCounter());
}
 
Example 11
Project: africastalking-android   File: NetworkUtils.java   Source Code and License 6 votes vote down vote up
public static boolean isBehindNAT() {
    String address = determineLocalIp();
    try {
        //       10.x.x.x | 192.168.x.x | 172.16.x.x .. 172.19.x.x
        byte[] d = InetAddress.getByName(address).getAddress();
        if ((d[0] == 10) ||
                (((0x000000FF & d[0]) == 172) &&
                        ((0x000000F0 & d[1]) == 16)) ||
                (((0x000000FF & d[0]) == 192) &&
                        ((0x000000FF & d[1]) == 168))) {
            return true;
        }
    } catch (UnknownHostException e) {
        Log.e("isBehindAT()" + address, e.getMessage() + "");
    }
    return false;
}
 
Example 12
Project: OpenJSharp   File: SnmpEngineImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Constructor. A Local Configuration Datastore is passed to the engine. It will be used to store and retrieve data (engine ID, engine boots).
 * <P> WARNING : The SnmpEngineId is computed as follow:
 * <ul>
 * <li> If an lcd file is provided containing the property "localEngineID", this property value is used.</li>.
 * <li> If not, a time based engineID is computed.</li>
 * </ul>
 * When no configuration nor java property is set for the engine ID value, a unique time based engine ID will be generated.
 * This constructor should be called by an <CODE>SnmpEngineFactory</CODE>. Don't call it directly.
 * @param fact The factory used to instantiate this engine.
 * @param lcd The local configuration datastore.
 */
public SnmpEngineImpl(SnmpEngineFactory fact,
                      SnmpLcd lcd) throws UnknownHostException {
    init(lcd, fact);
    initEngineID();
    if(engineid == null)
        engineid = SnmpEngineId.createEngineId();

    lcd.storeEngineId(engineid);

    if (SNMP_LOGGER.isLoggable(Level.FINER)) {
        SNMP_LOGGER.logp(Level.FINER, SnmpEngineImpl.class.getName(),
                "SnmpEngineImpl(SnmpEngineFactory,SnmpLcd)",
                "LOCAL ENGINE ID: " + engineid + " / " +
                "LOCAL ENGINE NB BOOTS: " + boot + " / " +
                "LOCAL ENGINE START TIME: " + getEngineTime());
    }
}
 
Example 13
Project: activiti-cloud-examples   File: EnglishCampaign.java   Source Code and License 6 votes vote down vote up
@Scheduled(fixedRate = 60000)
    public void logExecutions() throws UnknownHostException {
        logger.info("There are "+runtimeService.createExecutionQuery().count()+" process executions in RB instance on host "+ InetAddress.getLocalHost().getHostName());
        logger.info("There are "+runtimeService.createProcessInstanceQuery().processDefinitionKey("launchCampaign").count()+" launchCampaign process instances in RB instance on host "+ InetAddress.getLocalHost().getHostName());
        logger.info("There are "+runtimeService.createProcessInstanceQuery().processDefinitionKey("tweet-prize").count()+" tweet-prize process instances in RB instance on host "+ InetAddress.getLocalHost().getHostName());
        logger.info("There are "+taskService.createTaskQuery().count()+" tasks in RB instance on host "+ InetAddress.getLocalHost().getHostName());
/*        List<ProcessInstance> procInstanceList = runtimeService.createProcessInstanceQuery().orderByProcessInstanceId().asc().includeProcessVariables().list();
        for(ProcessInstance instance:procInstanceList) {
            logger.debug("Inspecting open process instance with id " + instance.getProcessInstanceId() + " for " + instance.getProcessDefinitionKey() + " started at " + instance.getStartTime());
            logger.debug("Instance suspended? " + instance.isSuspended()+" Instance ended? " + instance.isEnded());
            if (instance.getProcessVariables() != null && instance.getProcessVariables().size() > 0) {
                for (String varKey : instance.getProcessVariables().keySet()) {
                    logger.debug(instance.getProcessInstanceId()+" Variable - " + varKey + " - " + instance.getProcessVariables().get(varKey));
                }
            }
        }

        List<Execution> processExecutions = runtimeService.createExecutionQuery().list();
        for(Execution execution:processExecutions){
            logger.debug("Inspecting open process execution with id " + execution.getId() + " for proc inst " + execution.getRootProcessInstanceId());
            logger.debug("ParentId " + execution.getParentId()+" SuperExecutionId "+execution.getSuperExecutionId());
            logger.debug("Execution suspended? " + execution.isSuspended()+" Execution ended? " + execution.isEnded());
        }*/
    }
 
Example 14
Project: JWaves   File: RxNodeErrorHandlingCallAdapterFactory.java   Source Code and License 6 votes vote down vote up
private Throwable asRetrofitException(Throwable throwable) {
    if (throwable instanceof SocketTimeoutException) {
        return new ServerNotAvailableException();
    } else if (throwable instanceof UnknownHostException) {
        return new NoInternetConnectionException();
    } else if (throwable instanceof HttpException) {
        String url;
        HttpException httpException = (HttpException) throwable;
        if (httpException.response() != null) {
            url = httpException.response().raw().request().url().toString();
            ResponseBody body;
            if (httpException.response().isSuccessful())
                body = httpException.response().raw().body();
            else
                body = httpException.response().errorBody();

            try {
                ErrorNodeResponse error = parseNodeError(body);
                return new ApiNodeException(url, httpException.code(), error, httpException.getMessage());
            } catch (Throwable _ignore) {
                _ignore.printStackTrace();
            }
        }
    }
    return throwable;
}
 
Example 15
Project: CrawlerSYS   File: CrawlerServlet.java   Source Code and License 6 votes vote down vote up
/**
 * Initialization of the servlet. <br>
 *
 * @throws ServletException if an error occurs
 */
public void init() throws ServletException {
	String file = this.getServletContext().getRealPath(this.getInitParameter("log4j"));
	//从web.xml配置读取,名字一定要和web.xml配置一致
	  if(file != null){
	     PropertyConfigurator.configure(file);
	  }
	// Put your code here
	new CrawlerServer(DefaultConfig.serverPort).start();
	try {
		new WebSocket(DefaultConfig.socketPort).start();
	} catch (UnknownHostException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 16
Project: lams   File: HttpWebResponse.java   Source Code and License 6 votes vote down vote up
private void readResponseHeader( HttpURLConnection connection ) throws IOException {
    if (!needStatusWorkaround()) {
        _responseCode = connection.getResponseCode();
        _responseMessage = connection.getResponseMessage();
    } else {
         if (connection.getHeaderField(0) == null) throw new UnknownHostException( connection.getURL().toExternalForm() );

        StringTokenizer st = new StringTokenizer( connection.getHeaderField(0) );
        st.nextToken();
        if (!st.hasMoreTokens()) {
            _responseCode = HttpURLConnection.HTTP_OK;
            _responseMessage = "OK";
        } else try {
            _responseCode = Integer.parseInt( st.nextToken() );
            _responseMessage = getRemainingTokens( st );
        } catch (NumberFormatException e) {
            _responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
            _responseMessage = "Cannot parse response header";
        }
    }
}
 
Example 17
Project: gitplex-mit   File: GitPlex.java   Source Code and License 6 votes vote down vote up
public String guessServerUrl() {
	String hostName;
	try {
		hostName = InetAddress.getLocalHost().getHostName();
	} catch (UnknownHostException e) {
		throw new RuntimeException(e);
	}
	
	String serverUrl;
	if (serverConfig.getHttpPort() != 0)
		serverUrl = "http://" + hostName + ":" + serverConfig.getHttpPort();
	else 
		serverUrl = "https://" + hostName + ":" + serverConfig.getSslConfig().getPort();

	return StringUtils.stripEnd(serverUrl, "/");
}
 
Example 18
Project: hadoop   File: AmIpFilter.java   Source Code and License 6 votes vote down vote up
protected Set<String> getProxyAddresses() throws ServletException {
  long now = System.currentTimeMillis();
  synchronized(this) {
    if(proxyAddresses == null || (lastUpdate + updateInterval) >= now) {
      proxyAddresses = new HashSet<>();
      for (String proxyHost : proxyHosts) {
        try {
            for(InetAddress add : InetAddress.getAllByName(proxyHost)) {
              if (LOG.isDebugEnabled()) {
                LOG.debug("proxy address is: {}", add.getHostAddress());
              }
              proxyAddresses.add(add.getHostAddress());
            }
            lastUpdate = now;
          } catch (UnknownHostException e) {
            LOG.warn("Could not locate {} - skipping", proxyHost, e);
          }
        }
      if (proxyAddresses.isEmpty()) {
        throw new ServletException("Could not locate any of the proxy hosts");
      }
    }
    return proxyAddresses;
  }
}
 
Example 19
Project: jdk8u-jdk   File: NTLMAuthentication.java   Source Code and License 6 votes vote down vote up
private void init0() {

        hostname = java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction<String>() {
            public String run() {
                String localhost;
                try {
                    localhost = InetAddress.getLocalHost().getHostName().toUpperCase();
                } catch (UnknownHostException e) {
                     localhost = "localhost";
                }
                return localhost;
            }
        });
        int x = hostname.indexOf ('.');
        if (x != -1) {
            hostname = hostname.substring (0, x);
        }
    }
 
Example 20
Project: tifoon   File: ReflectionObjectTreeAwareTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testTracePathFromHost() throws UnknownHostException {
    final Port port1 = Port.from(Protocol.TCP, 23);
    final Port port2 = Port.from(Protocol.UDP, 53);

    final Map<InetAddress, List<Port>> inetAddressPortMap = new HashMap<>();
    inetAddressPortMap.put(InetAddress.getByName("1.5.3.6"), Collections.singletonList(port1));
    inetAddressPortMap.put(InetAddress.getByName("3.88.7.5"), Collections.singletonList(port2));

    final NetworkResult networkResult1 = new NetworkResult("network1", true, Collections.EMPTY_MAP);
    final NetworkResult networkResult2 = new NetworkResult("network2", true, inetAddressPortMap);

    final List<NetworkResult> networkResults = Arrays.asList(networkResult1, networkResult2);

    final PortScannerResult portScannerResult = new PortScannerResult(UUID.randomUUID().toString(), 0, 0, PortScannerStatus.DONE, Collections.EMPTY_LIST, "", networkResults);

    final List<ObjectTreeAware> path = portScannerResult.traceObjectPath(networkResult2.getOpenHosts().get("3.88.7.5"));

    Java6Assertions.assertThat(path).as("object path from host 3.88.7.5 to root").containsExactly(
            networkResult2,
            portScannerResult);
}
 
Example 21
Project: joal   File: StaticClientFilesTester.java   Source Code and License 5 votes vote down vote up
private static InetAddress createMockedINet6Address() {
    try {
        return InetAddress.getByName("fd2d:7212:4cd5:2f14:ffff:ffff:ffff:ffff");
    } catch (final UnknownHostException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 22
Project: QDrill   File: ServiceEngine.java   Source Code and License 5 votes vote down vote up
public DrillbitEndpoint start() throws DrillbitStartupException, UnknownHostException{
  int userPort = userServer.bind(config.getInt(ExecConstants.INITIAL_USER_PORT), allowPortHunting);
  String address = useIP ?  InetAddress.getLocalHost().getHostAddress() : InetAddress.getLocalHost().getCanonicalHostName();
  DrillbitEndpoint partialEndpoint = DrillbitEndpoint.newBuilder()
      .setAddress(address)
      //.setAddress("localhost")
      .setUserPort(userPort)
      .build();

  partialEndpoint = controller.start(partialEndpoint);
  return dataPool.start(partialEndpoint);
}
 
Example 23
Project: fuck_zookeeper   File: StaticHostProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Constructs a SimpleHostSet.
 * 
 * @param serverAddresses
 *            possibly unresolved ZooKeeper server addresses
 * @throws UnknownHostException
 * @throws IllegalArgumentException
 *             if serverAddresses is empty or resolves to an empty list
 */
public StaticHostProvider(Collection<InetSocketAddress> serverAddresses)
        throws UnknownHostException {
    for (InetSocketAddress address : serverAddresses) {
        InetAddress ia = address.getAddress();
        InetAddress resolvedAddresses[] = InetAddress.getAllByName((ia!=null) ? ia.getHostAddress():
            address.getHostName());
        for (InetAddress resolvedAddress : resolvedAddresses) {
            // If hostName is null but the address is not, we can tell that
            // the hostName is an literal IP address. Then we can set the host string as the hostname
            // safely to avoid reverse DNS lookup(???).
            // As far as i know, the only way to check if the hostName is null is use toString().
            // Both the two implementations of InetAddress are final class, so we can trust the return value of
            // the toString() method.
            if (resolvedAddress.toString().startsWith("/") 
                    && resolvedAddress.getAddress() != null) {
                this.serverAddresses.add(
                        new InetSocketAddress(InetAddress.getByAddress(
                                address.getHostName(),
                                resolvedAddress.getAddress()), 
                                address.getPort()));
            } else {
                this.serverAddresses.add(new InetSocketAddress(resolvedAddress.getHostAddress(), address.getPort()));
            }  
        }
    }
    
    if (this.serverAddresses.isEmpty()) {
        throw new IllegalArgumentException(
                "A HostProvider may not be empty!");
    }
    Collections.shuffle(this.serverAddresses);	
}
 
Example 24
Project: rskj   File: InetAddressTableTest.java   Source Code and License 5 votes vote down vote up
@Test
public void removeUnknownAddress() throws UnknownHostException {
    InetAddressTable table = new InetAddressTable();
    InetAddress address = generateIPAddressV4();

    table.removeAddress(address);
    Assert.assertFalse(table.contains(address));
}
 
Example 25
Project: jwala   File: ApplicationServiceImplTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() {
    groupId = new Identifier<Group>(1L);
    groupId2 = new Identifier<Group>(2L);
    group = new Group(groupId, "the-ws-group-name");
    group2 = new Group(groupId2, "the-ws-group-name-2");
    try {
        PowerMockito.mockStatic(JwalaUtils.class);
        PowerMockito.when(JwalaUtils.getHostAddress("testServer")).thenReturn(Inet4Address.getLocalHost().getHostAddress());
        PowerMockito.when(JwalaUtils.getHostAddress("testServer2")).thenReturn(Inet4Address.getLocalHost().getHostAddress());
    }catch (UnknownHostException ex){
        ex.printStackTrace();
    }
    when(Config.mockApplication.getId()).thenReturn(new Identifier<Application>(1L));
    when(Config.mockApplication.getWarPath()).thenReturn("the-ws-group-name/jwala-1.0.war");
    when(Config.mockApplication.getName()).thenReturn("jwala 1.0");
    when(Config.mockApplication.getGroup()).thenReturn(group);
    when(Config.mockApplication.getWebAppContext()).thenReturn("/jwala");
    when(Config.mockApplication.isSecure()).thenReturn(true);

    when(Config.mockApplication2.getId()).thenReturn(new Identifier<Application>(2L));
    when(Config.mockApplication2.getWarPath()).thenReturn("the-ws-group-name-2/jwala-1.1.war");
    when(Config.mockApplication2.getName()).thenReturn("jwala 1.1");
    when(Config.mockApplication2.getGroup()).thenReturn(group2);
    when(Config.mockApplication2.getWebAppContext()).thenReturn("/jwala");
    when(Config.mockApplication2.isSecure()).thenReturn(false);

    applications2.add(Config.mockApplication);
    applications2.add(Config.mockApplication2);

    ByteBuffer buf = java.nio.ByteBuffer.allocate(2); // 2 byte file
    buf.asShortBuffer().put((short) 0xc0de);

    uploadedFile = new ByteArrayInputStream(buf.array());

    SshConfiguration mockSshConfig = mock(SshConfiguration.class);
    sshConfig = mock(SshConfig.class);
    when(mockSshConfig.getUserName()).thenReturn("mockUser");
    when(sshConfig.getSshConfiguration()).thenReturn(mockSshConfig);
}
 
Example 26
Project: FirefoxData-android   File: SchemeSocketFactoryAdaptor.java   Source Code and License 5 votes vote down vote up
public Socket connectSocket(
        final Socket sock,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    final String host = remoteAddress.getHostName();
    final int port = remoteAddress.getPort();
    InetAddress local = null;
    int localPort = 0;
    if (localAddress != null) {
        local = localAddress.getAddress();
        localPort = localAddress.getPort();
    }
    return this.factory.connectSocket(sock, host, port, local, localPort, params);
}
 
Example 27
Project: jwala   File: JwalaUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
/**
 * Test IP from IP
 */
public void testIPv4Address() throws UnknownHostException{
    String host = Inet4Address.getLocalHost().getHostAddress();
    assertEquals(host,JwalaUtils.getHostAddress(host));
}
 
Example 28
Project: SkyEye   File: EsConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public TransportClient transportClient(Settings settings) {
    TransportClient client = TransportClient.builder().settings(settings).build();
    for (String ip : this.esProperties.getIps().split(Constants.COMMA)) {
        try {
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ip), this.esProperties.getPort()));
        } catch (UnknownHostException e) {
            LOGGER.error("es集群主机名错误, ip: {}", ip);
        }
    }
    return client;
}
 
Example 29
Project: dubbox-hystrix   File: NetUtils.java   Source Code and License 5 votes vote down vote up
/**
 * @param hostName
 * @return ip address or hostName if UnknownHostException 
 */
public static String getIpByHost(String hostName) {
    try{
        return InetAddress.getByName(hostName).getHostAddress();
    }catch (UnknownHostException e) {
        return hostName;
    }
}
 
Example 30
Project: rskj   File: PeerScoringManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void invalidBlockGivesBadReputationToNode() throws UnknownHostException {
    NodeID id = generateNodeID();
    PeerScoringManager manager = createPeerScoringManager();

    manager.recordEvent(id, null, EventType.INVALID_BLOCK);

    Assert.assertFalse(manager.hasGoodReputation(id));

    Assert.assertNotEquals(0, manager.getPeerScoring(id).getTimeLostGoodReputation());
}
 
Example 31
Project: incubator-servicecomb-java-chassis   File: SSLSocketFactoryExt.java   Source Code and License 5 votes vote down vote up
@Override
public Socket createSocket(String host, int port, InetAddress localHost,
    int localPort) throws IOException, UnknownHostException {
  return wrapSocket((SSLSocket) this.sslSocketFactory.createSocket(host,
      port,
      localHost,
      localPort));
}
 
Example 32
Project: BedrockProxy   File: RakNetUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Parses a single String as an address and port and converts it to an
 * <code>InetSocketAddress</code>.
 *
 * @param address     the address to convert.
 * @param defaultPort the default port to use if one is not specified.
 * @return the parsed <code>InetSocketAddress</code>.
 * @throws UnknownHostException if the address is in an invalid format or if the host cannot
 *                              be found.
 */
public static InetSocketAddress parseAddress(String address, int defaultPort) throws UnknownHostException {
    String[] addressSplit = address.split(":");
    if (addressSplit.length == 1 || addressSplit.length == 2) {
        InetAddress inetAddress = InetAddress.getByName(addressSplit[0]);
        int port = (addressSplit.length == 2 ? parseIntPassive(addressSplit[1]) : defaultPort);
        if (port >= 0 && port <= 65535) {
            return new InetSocketAddress(inetAddress, port);
        } else {
            throw new UnknownHostException("Port number must be between 0-65535");
        }
    } else {
        throw new UnknownHostException("Format must follow address:port");
    }
}
 
Example 33
Project: guava-mock   File: InetAddressesTest.java   Source Code and License 5 votes vote down vote up
public void testForStringIPv6Input() throws UnknownHostException {
  String ipStr = "3ffe::1";
  InetAddress ipv6Addr = null;
  // Shouldn't hit DNS, because it's an IP string literal.
  ipv6Addr = InetAddress.getByName(ipStr);
  assertEquals(ipv6Addr, InetAddresses.forString(ipStr));
  assertTrue(InetAddresses.isInetAddress(ipStr));
}
 
Example 34
Project: elasticsearch_my   File: IpRangeAggregatorTests.java   Source Code and License 5 votes vote down vote up
private static InetAddress randomIp(boolean v4) {
    try {
        if (v4) {
            byte[] ipv4 = new byte[4];
            random().nextBytes(ipv4);
            return InetAddress.getByAddress(ipv4);
        } else {
            byte[] ipv6 = new byte[16];
            random().nextBytes(ipv6);
            return InetAddress.getByAddress(ipv6);
        }
    } catch (UnknownHostException e) {
        throw new AssertionError();
    }
}
 
Example 35
Project: datatree   File: AbstractConverterSet.java   Source Code and License 5 votes vote down vote up
protected static final InetAddress toInetAddress(long number) {
	ByteBuffer b8 = ByteBuffer.allocate(8);
	b8.putLong(number);
	try {
		byte[] ipv4 = new byte[4];
		System.arraycopy(b8.array(), 0, ipv4, 0, 4);
		return InetAddress.getByAddress(ipv4);
	} catch (UnknownHostException e) {
		throw new IllegalArgumentException("Unable to convert \"" + number + "\" to InetAddress!");
	}
}
 
Example 36
Project: alfresco-repository   File: AlfrescoLdapSSLSocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException
{
    SSLSocket sslSocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port);
    addHostNameVerification(sslSocket);
    return sslSocket;
}
 
Example 37
Project: OpenJSharp   File: AclEntryImpl.java   Source Code and License 5 votes vote down vote up
private AclEntryImpl (AclEntryImpl i) throws UnknownHostException {
      setPrincipal(i.getPrincipal());
      permList = new Vector<Permission>();
      commList = new Vector<String>();

      for (Enumeration<String> en = i.communities(); en.hasMoreElements();){
        addCommunity(en.nextElement());
      }

      for (Enumeration<Permission> en = i.permissions(); en.hasMoreElements();){
        addPermission(en.nextElement());
      }
      if (i.isNegative()) setNegativePermissions();
}
 
Example 38
Project: ait-platform   File: AitTaskExcecutorBase.java   Source Code and License 5 votes vote down vote up
@Override
public void onApplicationEvent(final EmbeddedServletContainerInitializedEvent event) {
	try {
		serverPort = event.getEmbeddedServletContainer().getPort();
		serverIp = AitLocalhostIpAddress.search().getHostAddress();
	} catch (final UnknownHostException e) {
		e.printStackTrace();
	}
}
 
Example 39
Project: datatree   File: AbstractConverterSet.java   Source Code and License 5 votes vote down vote up
protected static final InetAddress toInetAddress(byte[] from) {
	try {
		return InetAddress.getByAddress(from);
	} catch (UnknownHostException e) {
		throw new IllegalArgumentException("Unable to convert byte array to InetAddress!");
	}
}
 
Example 40
Project: aos-FileCoreLibrary   File: UniAddress.java   Source Code and License 5 votes vote down vote up
static NbtAddress lookupServerOrWorkgroup( String name, InetAddress svr )
                                                throws UnknownHostException {
    Sem sem = new Sem( 2 );
    int type = NbtAddress.isWINS( svr ) ? 0x1b : 0x1d;

    QueryThread q1x = new QueryThread( sem, name, type, null, svr );
    QueryThread q20 = new QueryThread( sem, name, 0x20, null, svr );
    q1x.setDaemon( true );
    q20.setDaemon( true );
    try {
        synchronized( sem ) {
            q1x.start();
            q20.start();

            while( sem.count > 0 && q1x.ans == null && q20.ans == null ) {
                sem.wait();
            }
        }
    } catch( InterruptedException ie ) {
        throw new UnknownHostException( name );
    }
    if( q1x.ans != null ) {
        return q1x.ans;
    } else if( q20.ans != null ) {
        return q20.ans;
    } else {
        throw q1x.uhe;
    }
}
 
Example 41
Project: rapidminer   File: DefaultLicenseManager.java   Source Code and License 5 votes vote down vote up
private final byte[] getHardwareEntropy() {
    byte[] mac;
    try {
        InetAddress entropyEncoded = InetAddress.getLocalHost();
        if(entropyEncoded == null) {
            mac = DEF;
        } else {
            NetworkInterface digest = NetworkInterface.getByInetAddress(entropyEncoded);
            if(digest != null) {
                mac = digest.getHardwareAddress();
                if(mac == null) {
                    mac = DEF;
                }
            } else {
                mac = DEF;
            }
        }
    } catch (UnknownHostException | SocketException var5) {
        mac = DEF;
    }

    byte[] entropyEncoded1 = null;

    try {
        MessageDigest digest1 = MessageDigest.getInstance("SHA-512");
        digest1.reset();
        entropyEncoded1 = digest1.digest(mac);
    } catch (NoSuchAlgorithmException var4) {
        ;
    }

    return entropyEncoded1;
}
 
Example 42
Project: hadoop   File: DNS.java   Source Code and License 5 votes vote down vote up
/**
 * Determine the local hostname; retrieving it from cache if it is known
 * If we cannot determine our host name, return "localhost"
 * @return the local hostname or "localhost"
 */
private static String resolveLocalHostname() {
  String localhost;
  try {
    localhost = InetAddress.getLocalHost().getCanonicalHostName();
  } catch (UnknownHostException e) {
    LOG.warn("Unable to determine local hostname "
        + "-falling back to \"" + LOCALHOST + "\"", e);
    localhost = LOCALHOST;
  }
  return localhost;
}
 
Example 43
Project: irc-helper   File: NetSocket.java   Source Code and License 5 votes vote down vote up
NetSocket(String channel, String sender, String login, String hostname,
		String message, String args[], String Address, int port)
		throws UnknownHostException, IOException {
	this.caller = new Caller(channel, sender, login, hostname, message,
			message.split(" "));
	this.Address = Address;
	this.socket = new Socket(Address, port);
	this.id = new Integer(this.hashCode()).toString();
}
 
Example 44
Project: KernelHive   File: JobRunner.java   Source Code and License 5 votes vote down vote up
private void deployKernelIfExists(JobInfo jobInfo) {
	if (jobInfo.kernelString != null && !jobInfo.kernelString.equals("")) {
		Unit destUnit = unitServer.getProxy(jobInfo.unitID).getUnit();
		try {
			DataManager dp = new DataManager(jobInfo, destUnit.getHostname(), destUnit.getDataServerPort(), null);
			DataAddress dataAddress = dp.uploadData(jobInfo.kernelString, new DataAddress(jobInfo.clusterHost, 27017, null));
			jobInfo.kernelHost = dataAddress.hostname;
			jobInfo.kernelPort = dataAddress.port;
			jobInfo.kernelID = dataAddress.ID;
		} catch (UnknownHostException e) {
			logger.log(Level.SEVERE, null, e);
		}
	}
}
 
Example 45
Project: cas-server-4.2.1   File: ReverseDNSRunnable.java   Source Code and License 5 votes vote down vote up
/**
 * Runnable implementation to thread the work done in this class, allowing the
 * implementer to set a thread timeout and thereby short-circuit the lookup.
 */
@Override
public void run() {
    try {
        LOGGER.debug("Attempting to resolve {}", this.ipAddress);
        final InetAddress address = InetAddress.getByName(this.ipAddress);
        set(address.getCanonicalHostName());
    } catch (final UnknownHostException e) {
        /** N/A -- Default to IP address, but that's already done. **/
        LOGGER.debug("Unable to identify the canonical hostname for ip address.", e);
    }
}
 
Example 46
Project: 2017.1-Trezentos   File: ServerOperationEvaluationFragment.java   Source Code and License 5 votes vote down vote up
private boolean isInternetAvailable() {
    try {
        final InetAddress address = InetAddress.getByName("www.google.com");
        if(!address.equals("")){
            return true;
        }
        return !address.equals("");
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    return false;
}
 
Example 47
Project: sbiger-apm   File: MachineInfo.java   Source Code and License 5 votes vote down vote up
private static InetAddress getInetAddress() {
    try {
        return InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 48
Project: monarch   File: BucketOperatorImplTest.java   Source Code and License 5 votes vote down vote up
@Test
public void moveBucketShouldDelegateToParRegRebalanceOpMoveBucketForRegion()
    throws UnknownHostException {
  doReturn(true).when(rebalanceOp).moveBucketForRegion(sourceMember, targetMember, bucketId);

  operator.moveBucket(sourceMember, targetMember, bucketId, colocatedRegionBytes);

  verify(resourceObserver, times(1)).movingBucket(region, bucketId, sourceMember, targetMember);
  verify(rebalanceOp, times(1)).moveBucketForRegion(sourceMember, targetMember, bucketId);
}
 
Example 49
Project: OpenJSharp   File: Config.java   Source Code and License 5 votes vote down vote up
/**
 * Locate Kerberos realm using DNS
 *
 * @return the Kerberos realm
 */
private String getRealmFromDNS() throws KrbException {
    // use DNS to locate Kerberos realm
    String realm = null;
    String hostName = null;
    try {
        hostName = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException e) {
        KrbException ke = new KrbException(Krb5.KRB_ERR_GENERIC,
            "Unable to locate Kerberos realm: " + e.getMessage());
        ke.initCause(e);
        throw (ke);
    }
    // get the domain realm mapping from the configuration
    String mapRealm = PrincipalName.mapHostToRealm(hostName);
    if (mapRealm == null) {
        // No match. Try search and/or domain in /etc/resolv.conf
        List<String> srchlist = ResolverConfiguration.open().searchlist();
        for (String domain: srchlist) {
            realm = checkRealm(domain);
            if (realm != null) {
                break;
            }
        }
    } else {
        realm = checkRealm(mapRealm);
    }
    if (realm == null) {
        throw new KrbException(Krb5.KRB_ERR_GENERIC,
                            "Unable to locate Kerberos realm");
    }
    return realm;
}
 
Example 50
Project: elasticsearch_my   File: IpRangeAggregationBuilder.java   Source Code and License 5 votes vote down vote up
Range(String key, String mask) {
    String[] splits = mask.split("/");
    if (splits.length != 2) {
        throw new IllegalArgumentException("Expected [ip/prefix_length] but got [" + mask
                + "], which contains zero or more than one [/]");
    }
    InetAddress value = InetAddresses.forString(splits[0]);
    int prefixLength = Integer.parseInt(splits[1]);
    // copied from InetAddressPoint.newPrefixQuery
    if (prefixLength < 0 || prefixLength > 8 * value.getAddress().length) {
        throw new IllegalArgumentException("illegal prefixLength [" + prefixLength
                + "] in [" + mask + "]. Must be 0-32 for IPv4 ranges, 0-128 for IPv6 ranges");
    }
    // create the lower value by zeroing out the host portion, upper value by filling it with all ones.
    byte lower[] = value.getAddress();
    byte upper[] = value.getAddress();
    for (int i = prefixLength; i < 8 * lower.length; i++) {
        int m = 1 << (7 - (i & 7));
        lower[i >> 3] &= ~m;
        upper[i >> 3] |= m;
    }
    this.key = key;
    try {
        InetAddress fromAddress = InetAddress.getByAddress(lower);
        if (fromAddress.equals(InetAddressPoint.MIN_VALUE)) {
            this.from = null;
        } else {
            this.from = InetAddresses.toAddrString(fromAddress);
        }
        InetAddress inclusiveToAddress = InetAddress.getByAddress(upper);
        if (inclusiveToAddress.equals(InetAddressPoint.MAX_VALUE)) {
            this.to = null;
        } else {
            this.to = InetAddresses.toAddrString(InetAddressPoint.nextUp(inclusiveToAddress));
        }
    } catch (UnknownHostException bogus) {
        throw new AssertionError(bogus);
    }
}
 
Example 51
Project: sbc-qsystem   File: ClientNetProperty.java   Source Code and License 5 votes vote down vote up
@Override
public InetAddress getAddress() {
    InetAddress adr = null;
    try {
        adr = InetAddress.getByName(adress);
    } catch (UnknownHostException ex) {
        QLog.l().logger().error("Error!", ex);
    }
    return adr;
}
 
Example 52
Project: sbc-qsystem   File: FAdmin.java   Source Code and License 5 votes vote down vote up
@Override
public InetAddress getAddress() {
    InetAddress adr = null;
    try {
        adr = InetAddress.getByName(textFieldServerAddr.getText());
    } catch (UnknownHostException ex) {
        throw new ClientException("Error! " + ex);
    }
    return adr;
}
 
Example 53
Project: sbc-qsystem   File: Uses.java   Source Code and License 5 votes vote down vote up
/**
 * Послать сообщение по UDP широковещательно
 *
 * @param message текст посылаемого сообщения
 * @param port порт получателя
 */
public static void sendUDPBroadcast(String message, int port) {
    try {
        sendUDPMessage(message, InetAddress.getByName("255.255.255.255"), port);
    } catch (UnknownHostException ex) {
        throw new ServerException("Address issues " + ex.getMessage());
    }
}
 
Example 54
Project: AeroStory   File: CharSelectedWithPicHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {

    String pic = slea.readMapleAsciiString();
    int charId = slea.readInt();
    String macs = slea.readMapleAsciiString();
    c.updateMacs(macs);

    if (c.hasBannedMac()) {
        c.getSession().close(true);
        return;
    }
    if (c.checkPic(pic)) {
        if (c.getIdleTask() != null) {
            c.getIdleTask().cancel(true);
        }
        c.updateLoginState(MapleClient.LOGIN_SERVER_TRANSITION);

        String[] socket = Server.getInstance().getIP(c.getWorld(), c.getChannel()).split(":");
        try {
            c.announce(MaplePacketCreator.getServerIP(InetAddress.getByName(socket[0]), Integer.parseInt(socket[1]), charId));
        } catch (UnknownHostException | NumberFormatException e) {
        }
    } else {
        c.announce(MaplePacketCreator.wrongPic());
    }
}
 
Example 55
Project: googles-monorepo-demo   File: InetAddressesTest.java   Source Code and License 5 votes vote down vote up
public void testIsMaximum() throws UnknownHostException {
  InetAddress address = InetAddress.getByName("255.255.255.254");
  assertFalse(InetAddresses.isMaximum(address));

  address = InetAddress.getByName("255.255.255.255");
  assertTrue(InetAddresses.isMaximum(address));

  address = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe");
  assertFalse(InetAddresses.isMaximum(address));

  address = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff");
  assertTrue(InetAddresses.isMaximum(address));
}
 
Example 56
Project: monarch   File: HostStatHelper.java   Source Code and License 5 votes vote down vote up
/**
 * @return this machine's fully qualified hostname or "unknownHostName" if one cannot be found.
 */
private static String getHostSystemName() {
  String hostname = "unknownHostName";
  try {
    InetAddress addr = SocketCreator.getLocalHost();
    hostname = addr.getCanonicalHostName();
  } catch (UnknownHostException uhe) {
  }
  return hostname;
}
 
Example 57
Project: azure-libraries-for-java   File: AppServiceDomainImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Observable<AppServiceDomain> createResourceAsync() {
    String[] domainParts = this.name().split("\\.");
    String topLevel = domainParts[domainParts.length - 1];
    final DomainsInner client = this.manager().inner().domains();
    return this.manager().inner().topLevelDomains().listAgreementsAsync(topLevel, new TopLevelDomainAgreementOptionInner())
            // Step 1: Consent to agreements
            .flatMap(new Func1<Page<TldLegalAgreementInner>, Observable<List<String>>>() {
                @Override
                public Observable<List<String>> call(Page<TldLegalAgreementInner> tldLegalAgreementInnerPage) {
                    List<String> agreementKeys = new ArrayList<String>();
                    for (TldLegalAgreementInner agreementInner : tldLegalAgreementInnerPage.items()) {
                        agreementKeys.add(agreementInner.agreementKey());
                    }
                    return Observable.just(agreementKeys);
                }
            })
            // Step 2: Create domain
            .flatMap(new Func1<List<String>, Observable<DomainInner>>() {
                @Override
                public Observable<DomainInner> call(List<String> keys) {
                    try {
                        inner().withConsent(new DomainPurchaseConsent()
                                .withAgreedAt(new DateTime())
                                .withAgreedBy(Inet4Address.getLocalHost().getHostAddress())
                                .withAgreementKeys(keys));
                    } catch (UnknownHostException e) {
                        return Observable.error(e);
                    }
                    return client.createOrUpdateAsync(resourceGroupName(), name(), inner());
                }
            })
            .map(innerToFluentMap(this));
}
 
Example 58
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: BrokerConfig.java   Source Code and License 5 votes vote down vote up
public static String localHostName() {
    try {
        return InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    return "DEFAULT_BROKER";
}
 
Example 59
Project: hadoop   File: NNStorage.java   Source Code and License 5 votes vote down vote up
/**
 * Generate new blockpoolID.
 * 
 * @return new blockpoolID
 */ 
static String newBlockPoolID() throws UnknownHostException{
  String ip = "unknownIP";
  try {
    ip = DNS.getDefaultIP("default");
  } catch (UnknownHostException e) {
    LOG.warn("Could not find ip address of \"default\" inteface.");
    throw e;
  }
  
  int rand = DFSUtil.getSecureRandom().nextInt(Integer.MAX_VALUE);
  String bpid = "BP-" + rand + "-"+ ip + "-" + Time.now();
  return bpid;
}
 
Example 60
Project: opencron   File: IPUtils.java   Source Code and License 5 votes vote down vote up
public static String getIpAddr(HttpServletRequest request) {
    String ipAddress = request.getHeader("x-forwarded-for");
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getRemoteAddr();
        if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
            //根据网卡取本机配置的IP
            InetAddress inet = null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            ipAddress = inet.getHostAddress();
        }
    }
    //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
    if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
        if (ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }
    }
    return ipAddress;
}