Java Code Examples for java.net.InetAddress.getByName()

The following are Jave code examples for showing how to use getByName() of the java.net.InetAddress class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openjdk-jdk10   File: JMXAgentInterfaceBinding.java   View Source Code Vote up 6 votes
public static void main(String[] args) {
    if (args.length != 4) {
        throw new RuntimeException(
                "Test failed. usage: java JMXInterfaceBindingTest <BIND_ADDRESS> <JMX_PORT> <RMI_PORT> {true|false}");
    }
    int jmxPort = parsePortFromString(args[1]);
    int rmiPort = parsePortFromString(args[2]);
    boolean useSSL = Boolean.parseBoolean(args[3]);
    String strBindAddr = args[0];
    System.out.println(
            "DEBUG: Running test for triplet (hostname,jmxPort,rmiPort) = ("
                    + strBindAddr + "," + jmxPort + "," + rmiPort + "), useSSL = " + useSSL);
    InetAddress bindAddress;
    try {
        bindAddress = InetAddress.getByName(args[0]);
    } catch (UnknownHostException e) {
        throw new RuntimeException("Test failed. Unknown ip: " + args[0]);
    }
    JMXAgentInterfaceBinding test = new JMXAgentInterfaceBinding(bindAddress,
            jmxPort, rmiPort, useSSL);
    test.startEndpoint(); // Expect for main test to terminate process
}
 
Example 2
Project: LivroJavaComoProgramar10Edicao   File: TicTacToeClient.java   View Source Code Vote up 6 votes
public void startClient()
{
   try // connect to server and get streams
   {
      // make connection to server
      connection = new Socket(
         InetAddress.getByName(ticTacToeHost), 12345);

      // get streams for input and output
      input = new Scanner(connection.getInputStream());
      output = new Formatter(connection.getOutputStream());
   } 
   catch (IOException ioException)
   {
      ioException.printStackTrace();         
   } 

   // create and start worker thread for this client
   ExecutorService worker = Executors.newFixedThreadPool(1);
   worker.execute(this); // execute client
}
 
Example 3
Project: T0rlib4Android   File: Socks5Message.java   View Source Code Vote up 6 votes
/**
 * Writes the message to the stream.
 * 
 * @param out
 *            Output stream to which message should be written.
 */
public void write(OutputStream out) throws SocksException, IOException {
	if (data == null) {
		Socks5Message msg;

		if (addrType == SOCKS_ATYP_DOMAINNAME) {
			msg = new Socks5Message(command, host, port);
		} else {
			if (ip == null) {
				try {
					ip = InetAddress.getByName(host);
				} catch (final UnknownHostException uh_ex) {
					throw new SocksException(
							SocksProxyBase.SOCKS_JUST_ERROR);
				}
			}
			msg = new Socks5Message(command, ip, port);
		}
		data = msg.data;
	}
	out.write(data);
}
 
Example 4
Project: emergentmud   File: MainResource.java   View Source Code Vote up 6 votes
private String extractRemoteIp(HttpServletRequest request) {
    String forwardedHeader = request.getHeader("x-forwarded-for");

    if (forwardedHeader != null) {
        String[] addresses = forwardedHeader.split("[,]");

        for (String address : addresses) {
            try {
                InetAddress inetAddress = InetAddress.getByName(address);

                if (!inetAddress.isSiteLocalAddress()) {
                    return inetAddress.getHostAddress();
                }
            } catch (UnknownHostException e) {
                LOGGER.debug("Failed to resolve IP for address: {}", address);
            }
        }
    }

    return request.getRemoteAddr();
}
 
Example 5
Project: aos-FileCoreLibrary   File: Config.java   View Source Code Vote up 6 votes
public static InetAddress getLocalHost() {
    String addr = prp.getProperty( "jcifs.smb.client.laddr" );

    if (addr != null) {
        try {
            return InetAddress.getByName( addr );
        } catch( UnknownHostException uhe ) {
            if( log.level > 0 ) {
                log.println( "Ignoring jcifs.smb.client.laddr address: " + addr );
                uhe.printStackTrace( log );
            }
        }
    }

    return null;
}
 
Example 6
Project: hadoop   File: TestRackResolver.java   View Source Code Vote up 6 votes
@Test
public void testCaching() {
  Configuration conf = new Configuration();
  conf.setClass(
    CommonConfigurationKeysPublic.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY,
    MyResolver.class, DNSToSwitchMapping.class);
  RackResolver.init(conf);
  try {
    InetAddress iaddr = InetAddress.getByName("host1");
    MyResolver.resolvedHost1 = iaddr.getHostAddress();
  } catch (UnknownHostException e) {
    // Ignore if not found
  }
  Node node = RackResolver.resolve("host1");
  Assert.assertEquals("/rack1", node.getNetworkLocation());
  node = RackResolver.resolve("host1");
  Assert.assertEquals("/rack1", node.getNetworkLocation());
  node = RackResolver.resolve(invalidHost);
  Assert.assertEquals(NetworkTopology.DEFAULT_RACK, node.getNetworkLocation());
}
 
Example 7
Project: AndroidVideoCache   File: HttpProxyCacheServer.java   View Source Code Vote up 6 votes
private HttpProxyCacheServer(Config config) {
    this.config = checkNotNull(config);
    try {
        InetAddress inetAddress = InetAddress.getByName(PROXY_HOST);
        this.serverSocket = new ServerSocket(0, 8, inetAddress);
        this.port = serverSocket.getLocalPort();
        IgnoreHostProxySelector.install(PROXY_HOST, port);
        CountDownLatch startSignal = new CountDownLatch(1);
        this.waitConnectionThread = new Thread(new WaitRequestsRunnable(startSignal));
        this.waitConnectionThread.start();
        startSignal.await(); // freeze thread, wait for server starts
        this.pinger = new Pinger(PROXY_HOST, port);
        LOG.info("Proxy cache server started. Is it alive? " + isAlive());
    } catch (IOException | InterruptedException e) {
        socketProcessor.shutdown();
        throw new IllegalStateException("Error starting local proxy server", e);
    }
}
 
Example 8
Project: guava-mock   File: InetAddressesTest.java   View Source Code Vote up 6 votes
public void testDecrementIPv4() throws UnknownHostException {
  InetAddress address660 = InetAddress.getByName("172.24.66.0");
  InetAddress address66255 = InetAddress.getByName("172.24.66.255");
  InetAddress address670 = InetAddress.getByName("172.24.67.0");

  InetAddress address = address670;
  address = InetAddresses.decrement(address);

  assertEquals(address66255, address);

  for (int i = 0; i < 255; i++) {
    address = InetAddresses.decrement(address);
  }
  assertEquals(address660, address);

  InetAddress address0000 = InetAddress.getByName("0.0.0.0");
  address = address0000;
  try {
    address = InetAddresses.decrement(address);
    fail();
  } catch (IllegalArgumentException expected) {}
}
 
Example 9
Project: lsascan_v1.0_linux   File: Lsascan_v1_frame.java   View Source Code Vote up 5 votes
public void scaniprange2fun() {
   	int ipthreadnums = Integer.parseInt(ipthreads.getText().trim());
   	String striii;
	//System.out.println(tip2);
	InetAddress tipordomain2 = null;
	//System.out.println(ipordomain.getText().trim());
	try {
		tipordomain2 = InetAddress.getByName(ipordomain.getText().trim());
	} catch (UnknownHostException e1) {
		// TODO Auto-generated catch block
		//e1.printStackTrace();
	}
	String tip2 = tipordomain2.getHostAddress();
	//System.out.print(tip2);
	for(int iii=1;iii<=254;iii++) {
		striii = Integer.toString(iii);
		Lsaipscan.Scaniprange2.allipp.offer(tip2.split("\\.")[0]+"."+tip2.split("\\.")[1]+"."+tip2.split("\\.")[2]+"."+striii);
		//System.out.print(tip2.split("\\.")[0]+tip2.split("\\.")[1]+"."+tip2.split("\\.")[2]+striii);
	}
	
	iparea.append("----------------Total ip nums: 254------------------\n");
	
	   
	   ExecutorService executor = Executors.newFixedThreadPool(ipthreadnums);
	   for (int i = 0; i < ipthreadnums; i++) {
		   Scaniprange2 scaniprange2 = new Scaniprange2();
           executor.execute(scaniprange2);
        }
	   executor.shutdown();
        try {
            while (!executor.isTerminated()) {
                Thread.sleep(1000);
            }
        } catch (Exception e2) {
            //e2.printStackTrace();
        }
    iparea.append("----------------Over!!!------------------\n");
}
 
Example 10
Project: DecompiledMinecraft   File: RConThreadMain.java   View Source Code Vote up 5 votes
/**
 * Creates a new Thread object from this class and starts running
 */
public void startThread()
{
    if (0 == this.rconPassword.length())
    {
        this.logWarning("No rcon password set in \'" + this.server.getSettingsFilename() + "\', rcon disabled!");
    }
    else if (0 < this.rconPort && 65535 >= this.rconPort)
    {
        if (!this.running)
        {
            try
            {
                this.serverSocket = new ServerSocket(this.rconPort, 0, InetAddress.getByName(this.hostname));
                this.serverSocket.setSoTimeout(500);
                super.startThread();
            }
            catch (IOException ioexception)
            {
                this.logWarning("Unable to initialise rcon on " + this.hostname + ":" + this.rconPort + " : " + ioexception.getMessage());
            }
        }
    }
    else
    {
        this.logWarning("Invalid rcon port " + this.rconPort + " found in \'" + this.server.getSettingsFilename() + "\', rcon disabled!");
    }
}
 
Example 11
Project: multicast   File: TiandeMulticastSocket.java   View Source Code Vote up 5 votes
public static void setGroup(String group) {
	try {
		TiandeMulticastSocket.group = InetAddress.getByName(group);
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}
 
Example 12
Project: github-test   File: MulticastRegistry.java   View Source Code Vote up 5 votes
private void unicast(String msg, String host) {
    if (logger.isInfoEnabled()) {
        logger.info("Send unicast message: " + msg + " to " + host + ":" + mutilcastPort);
    }
    try {
        byte[] data = (msg + "\n").getBytes();
        DatagramPacket hi = new DatagramPacket(data, data.length, InetAddress.getByName(host), mutilcastPort);
        mutilcastSocket.send(hi);
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example 13
Project: openrasp   File: SyslogTcpAppender.java   View Source Code Vote up 5 votes
static
InetAddress getAddressByName(String host) {
  try {
    return InetAddress.getByName(host);
  } catch(Exception e) {
    if (e instanceof InterruptedIOException || e instanceof InterruptedException) {
        Thread.currentThread().interrupt();
    }
    LogLog.error("Could not find address of ["+host+"].", e);
    return null;
  }
}
 
Example 14
Project: scorekeeperfrontend   File: DiscoveryTest.java   View Source Code Vote up 5 votes
@Test
public void testIPChange() throws Exception
{
    UUID uuid = UUID.fromString("abd86e8a-cf47-11e7-abc4-cec278b6b50a");
    byte d1[] = ("[{ \"service\":\"DATABASE\", \"serverid\":\""+uuid+"\", \"data\":{\"hostname\": \"d1\"}}]").getBytes();
    InetAddress a1 = InetAddress.getByName("192.168.1.10");
    InetAddress a2 = InetAddress.getByName("192.168.1.20");

    totest.addServiceListener((serverid, service, jsondata, up) -> {
        System.out.println(serverid + ", " + service + ", " + jsondata + ", " + up);
        if (up) {
            activeuuid = serverid;
            activeip = (InetAddress)jsondata.get("ip");
        } else {
            activeuuid = null;
            activeip = null;
        }
    });

    // message with a1 address
    totest.processNetworkData(a1, d1, d1.length);
    Assert.assertEquals(uuid, activeuuid);
    Assert.assertEquals(a1, activeip);

    // message with a2 addrses
    totest.processNetworkData(a2, d1, d1.length);
    Assert.assertEquals(uuid, activeuuid);
    Assert.assertEquals(a2, activeip);

    // now check a timeout
    Thread.sleep(200);
    Assert.assertEquals(uuid, activeuuid);
    Assert.assertEquals(a2, activeip);

    totest.checkForTimeouts();
    Assert.assertEquals(null, activeuuid);
    Assert.assertEquals(null, activeip);
}
 
Example 15
Project: OperatieBRP   File: SystemSslSocketFactory.java   View Source Code Vote up 5 votes
/**
 * Create a server socket.
 * @param serviceUrl jmx service url
 * @return server socket
 * @throws IOException if an I/O error occurs when creating the socket
 */
@Override
public ServerSocket createServerSocket(final JMXServiceURL serviceUrl) throws IOException {
    final InetAddress host = InetAddress.getByName(serviceUrl.getHost());
    final SSLServerSocket baseSslServerSocket = (SSLServerSocket) sslContext.getServerSocketFactory()
            .createServerSocket(serviceUrl.getPort(), 0, host);

    LOGGER.log(Level.FINE, "Created server socket");
    return baseSslServerSocket;
}
 
Example 16
Project: LoRaWAN-Smart-Parking   File: HttpAuthenticator.java   View Source Code Vote up 4 votes
private InetAddress getConnectToInetAddress(Proxy proxy, URL url) throws IOException {
  return (proxy != null && proxy.type() != Proxy.Type.DIRECT)
      ? ((InetSocketAddress) proxy.address()).getAddress()
      : InetAddress.getByName(url.getHost());
}
 
Example 17
Project: FF14_ScraperChat   File: PacketInstance.java   View Source Code Vote up 4 votes
/**
 * ��Ʈ��ũ ��Ŷ �ʱ�ȭ
 * 
 * @return PcapHandle
 */
public PcapHandle packetInit() {

	PcapHandle handle = null;
	String connIP = null;
	String reg = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";

	try {
		
		// ���� IP �ּ�
		InetAddress local = InetAddress.getLocalHost();
		String localP = local.getHostAddress();
		
		List<String> list = new ArrayList<String>();
		List<String> ip_list = getLocalServerIp();
		for(int i = 0; i < ip_list.size(); i++) {
			if(ip_list.get(i).matches(reg)) {
				System.out.println(ip_list.get(i));
				list.add(ip_list.get(i));
			}
		}
		
		// �ӽ��� ���� �����ǰ� 1���̻��϶�.
		if(list.size() > 1) {
			for(int i = 0; i < list.size(); i++) {
				if(!list.get(i).equals(localP)) {
					// ���� �����ǰ� �ƴѰ�,
					connIP = list.get(i);
				}
			}
		} else {
			connIP = localP;
		}
		
		System.out.println("�������� ������: " + connIP);
		
		// �����ϰ��� �ϴ� �������̽� ����
		InetAddress addr = InetAddress.getByName(connIP);
		PcapNetworkInterface nif = Pcaps.getDevByAddress(addr);
		
		// ��Ŷ��� �ڵ鷯 ����
		PromiscuousMode mode = PromiscuousMode.PROMISCUOUS;
		handle = nif.openLive(SNAPLEN, mode, TIME_OUT);

	} catch (Exception e) {
		e.printStackTrace();
	}

	return handle;

}
 
Example 18
Project: parabuild-ci   File: HsqlSocketFactory.java   View Source Code Vote up 2 votes
/**
 * Returns a server socket bound to the specified port.
 * The socket is configured with the socket options
 * given to this factory.
 *
 * @return the ServerSocket
 * @param port the port to which to bind the ServerSocket
 * @throws Exception if a network error occurs
 */
public ServerSocket createServerSocket(int port,
                                       String address) throws Exception {
    return new ServerSocket(port, 128, InetAddress.getByName(address));
}
 
Example 19
Project: Biliomi   File: CallbackServer.java   View Source Code Vote up 2 votes
/**
 * Start a server listening for request on redirectHost:redirectPort
 *
 * @param accessTokenParamName The Query parameter name of the access token returned by the oauth callback, e.g. "access_token" or "code"
 * @throws IOException When an exception occurs reading/writing to/from a socket
 */
public void awaitAuthorization(String accessTokenParamName) throws IOException {
  serverSocket = new ServerSocket(resources.getCallbackPort(), 0, InetAddress.getByName(resources.getCallbackHost()));
  runCallbackServer(accessTokenParamName);
}
 
Example 20
Project: xdman   File: FTPClient.java   View Source Code Vote up 2 votes
/**
 * Set the external IP address in active mode.
 * Useful when there are multiple network cards.
 * <p>
 * @param ipAddress The external IP address of this machine.
 * @throws UnknownHostException if the ipAddress cannot be resolved
 * @since 2.2
 */
public void setActiveExternalIPAddress(String ipAddress) throws UnknownHostException
{
    this.__activeExternalHost = InetAddress.getByName(ipAddress);
}