类java.net.InetAddress源码实例Demo

下面列出了怎么用java.net.InetAddress的API类实例代码及写法,或者点击链接到github查看源代码。

@Override
public Optional<EndpointMetadata> endpointMetadata(final InetAddress endpoint) {
    final IEndpointSnitch endpointSnitch = DatabaseDescriptor.getEndpointSnitch();

    return Optional.of(new EndpointMetadata() {
        @Override
        public String dataCenter() {
            return endpointSnitch.getDatacenter(endpoint);
        }

        @Override
        public String rack() {
            return endpointSnitch.getRack(endpoint);
        }
    });
}
 
源代码2 项目: Flink-CEPplus   文件: AbstractServerBase.java
/**
 * Creates the {@link AbstractServerBase}.
 *
 * <p>The server needs to be started via {@link #start()}.
 *
 * @param serverName the name of the server
 * @param bindAddress address to bind to
 * @param bindPortIterator port to bind to
 * @param numEventLoopThreads number of event loop threads
 */
protected AbstractServerBase(
		final String serverName,
		final InetAddress bindAddress,
		final Iterator<Integer> bindPortIterator,
		final Integer numEventLoopThreads,
		final Integer numQueryThreads) {

	Preconditions.checkNotNull(bindPortIterator);
	Preconditions.checkArgument(numEventLoopThreads >= 1, "Non-positive number of event loop threads.");
	Preconditions.checkArgument(numQueryThreads >= 1, "Non-positive number of query threads.");

	this.serverName = Preconditions.checkNotNull(serverName);
	this.bindAddress = Preconditions.checkNotNull(bindAddress);
	this.numEventLoopThreads = numEventLoopThreads;
	this.numQueryThreads = numQueryThreads;

	this.bindPortRange = new HashSet<>();
	while (bindPortIterator.hasNext()) {
		int port = bindPortIterator.next();
		Preconditions.checkArgument(port >= 0 && port <= 65535,
				"Invalid port configuration. Port must be between 0 and 65535, but was " + port + ".");
		bindPortRange.add(port);
	}
}
 
源代码3 项目: arcusplatform   文件: BaseCassandraModule.java
private static List<InetAddress> parseContactPoints(String commaDelimitedList) {
    List<InetAddress> contactPoints = new ArrayList<>();

    String[] cps = commaDelimitedList.split(",");
    for (int i = 0; i < cps.length; i++) {
        try {
            InetAddress[] addrs = InetAddress.getAllByName(cps[i].trim());
            LOGGER.debug("{} resolves to: {}", cps[i], addrs);

            for (InetAddress addr : addrs) {
                contactPoints.add(addr);
            }
        } catch (UnknownHostException ex) {
            // ignore so we can use any working addresses
            // that are available.
        }
    }

    if (contactPoints.isEmpty()) {
        throw new RuntimeException("Unable to configure Cassandra cluster, the hosts specified in cassandra.contactPoints could not be resolved");
    }

    return contactPoints;
}
 
源代码4 项目: ReactiveLab   文件: AbstractMiddleTierService.java
protected InstanceInfo createInstanceInfo(int port) {
    final HashSet<ServicePort> ports = new HashSet<>(Arrays.asList(new ServicePort(port, false)));

    String hostAddress = "unknown";
    try {
        hostAddress = InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        e.printStackTrace();
        hostAddress = "unknown-" + UUID.randomUUID();
    }

    return new InstanceInfo.Builder()
            .withId(hostAddress + "-" + port)
            .withApp("reactive-lab")
            .withStatus(InstanceInfo.Status.UP)
            .withVipAddress(eurekaVipAddress)
            .withPorts(ports)
            .withDataCenterInfo(BasicDataCenterInfo.fromSystemData())
            .build();
}
 
源代码5 项目: JavaLinuxNet   文件: libcTest.java
@Test
public void testin_addr() throws Exception {
    libc.in_addr a;
    a=new libc.in_addr();
    Assert.assertEquals(0, a.address);

    a=new libc.in_addr(0x01020304);
    Assert.assertEquals(0x01020304, a.address);
    InetAddress ax=a.toInetAddress();
    Assert.assertNotNull(ax);
    Assert.assertEquals("/1.2.3.4", ax.toString());
    Assert.assertEquals("0x01020304",a.toString());

    a=new libc.in_addr(0xfffffffe);
    Assert.assertEquals(0xfffffffe, a.address);
    ax=a.toInetAddress();
    Assert.assertNotNull(ax);
    Assert.assertEquals("/255.255.255.254", ax.toString());
    Assert.assertEquals("0xfffffffe",a.toString());

}
 
源代码6 项目: hottub   文件: IPAddressName.java
/**
 * Parse an IPv4 address.
 *
 * @param name IPv4 address with optional mask values
 * @throws IOException on error
 */
private void parseIPv4(String name) throws IOException {

    // Parse name into byte-value address components
    int slashNdx = name.indexOf('/');
    if (slashNdx == -1) {
        address = InetAddress.getByName(name).getAddress();
    } else {
        address = new byte[8];

        // parse mask
        byte[] mask = InetAddress.getByName
            (name.substring(slashNdx+1)).getAddress();

        // parse base address
        byte[] host = InetAddress.getByName
            (name.substring(0, slashNdx)).getAddress();

        System.arraycopy(host, 0, address, 0, 4);
        System.arraycopy(mask, 0, address, 4, 4);
    }
}
 
源代码7 项目: kylin   文件: NetworkUtils.java
public static String getLocalIp() {
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint())
                continue;
            if (iface.getName().startsWith("vboxnet"))
                continue;

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                final String ip = addr.getHostAddress();
                if (Inet4Address.class == addr.getClass())
                    return ip;
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
    return null;
}
 
源代码8 项目: jdk8u-jdk   文件: SdpProvider.java
private void convertTcpToSdpIfMatch(FileDescriptor fdObj,
                                           Action action,
                                           InetAddress address,
                                           int port)
    throws IOException
{
    boolean matched = false;
    for (Rule rule: rules) {
        if (rule.match(action, address, port)) {
            SdpSupport.convertSocket(fdObj);
            matched = true;
            break;
        }
    }
    if (log != null) {
        String addr = (address instanceof Inet4Address) ?
            address.getHostAddress() : "[" + address.getHostAddress() + "]";
        if (matched) {
            log.format("%s to %s:%d (socket converted to SDP protocol)\n", action, addr, port);
        } else {
            log.format("%s to %s:%d (no match)\n", action, addr, port);
        }
    }
}
 
private static ServiceRequestContext newServiceContext(
        String path, @Nullable String query) throws Exception {

    final InetSocketAddress remoteAddress = new InetSocketAddress(
            InetAddress.getByAddress("client.com", new byte[] { 1, 2, 3, 4 }), 5678);
    final InetSocketAddress localAddress = new InetSocketAddress(
            InetAddress.getByAddress("server.com", new byte[] { 5, 6, 7, 8 }), 8080);

    final String pathAndQuery = path + (query != null ? '?' + query : "");
    final HttpRequest req = HttpRequest.of(RequestHeaders.of(HttpMethod.GET, pathAndQuery,
                                                             HttpHeaderNames.AUTHORITY, "server.com:8080",
                                                             HttpHeaderNames.USER_AGENT, "some-client"));

    final ServiceRequestContext ctx =
            ServiceRequestContext.builder(req)
                                 .sslSession(newSslSession())
                                 .remoteAddress(remoteAddress)
                                 .localAddress(localAddress)
                                 .proxiedAddresses(
                                         ProxiedAddresses.of(new InetSocketAddress("9.10.11.12", 0)))
                                 .build();

    ctx.setAttr(MY_ATTR, new CustomObject("some-name", "some-value"));
    return ctx;
}
 
源代码10 项目: openjdk-jdk9   文件: HashSpread.java
/**
 * Generate and return a random IPv6 address.
 */
static InetAddress randomIPv6Adress() {
    StringBuffer sb = new StringBuffer();

    for (int i=0; i<8; i++) {

        if (i > 0)
            sb.append(":");

        for (int j=0; j<4; j++) {
            int v = r.nextInt(16);
            if (v < 10) {
                sb.append(Integer.toString(v));
            } else {
                char c = (char) ('A' + v - 10);
                sb.append(c);
            }
        }
    }

    try {
        return InetAddress.getByName(sb.toString());
    } catch (UnknownHostException x) {
        throw new Error("Internal error in test");
    }
}
 
源代码11 项目: onos   文件: LsRequest.java
/**
 * Gets LS request packet body as byte array.
 *
 * @return LS request packet body as byte array
 */
public byte[] getLsrBodyAsByteArray() {
    List<Byte> bodyLst = new ArrayList<>();

    try {
        for (LsRequestPacket lsrPacket : linkStateRequests) {
            bodyLst.addAll(Bytes.asList(OspfUtil.convertToFourBytes(lsrPacket.lsType())));
            bodyLst.addAll(Bytes.asList(InetAddress.getByName(lsrPacket.linkStateId()).getAddress()));
            bodyLst.addAll(Bytes.asList(InetAddress.getByName(lsrPacket.ownRouterId()).getAddress()));
        }
    } catch (Exception e) {
        log.debug("Error::getLsrBodyAsByteArray {}", e.getMessage());
        return Bytes.toArray(bodyLst);
    }

    return Bytes.toArray(bodyLst);
}
 
源代码12 项目: lavaplayer   文件: ExtendedConnectionOperator.java
private InetAddress[] resolveAddresses(HttpHost host, HttpContext context) throws IOException {
  if (host.getAddress() != null) {
    return new InetAddress[] { host.getAddress() };
  }

  Object resolvedObject = context.getAttribute(RESOLVED_ADDRESSES);

  if (resolvedObject instanceof ResolvedAddresses) {
    ResolvedAddresses resolved = (ResolvedAddresses) resolvedObject;

    if (resolved.host.equals(host)) {
      return resolved.addresses;
    }
  }

  return dnsResolver.resolve(host.getHostName());
}
 
源代码13 项目: openjdk-jdk9   文件: InitialToken.java
private byte[] getAddrBytes(InetAddress addr) throws GSSException {
    int addressType = getAddrType(addr);
    byte[] addressBytes = addr.getAddress();
    if (addressBytes != null) {
        switch (addressType) {
            case CHANNEL_BINDING_AF_INET:
                if (addressBytes.length != Inet4_ADDRSZ) {
                    throw new GSSException(GSSException.FAILURE, -1,
                    "Incorrect AF-INET address length in ChannelBinding.");
                }
                return (addressBytes);
            case CHANNEL_BINDING_AF_INET6:
                if (addressBytes.length != Inet6_ADDRSZ) {
                    throw new GSSException(GSSException.FAILURE, -1,
                    "Incorrect AF-INET6 address length in ChannelBinding.");
                }
                return (addressBytes);
            default:
                throw new GSSException(GSSException.FAILURE, -1,
                "Cannot handle non AF-INET addresses in ChannelBinding.");
        }
    }
    return null;
}
 
源代码14 项目: hottub   文件: Inet6AddressSerializationTest.java
static void testAllNetworkInterfaces() throws Exception {
    System.err.println("\n testAllNetworkInterfaces: \n ");
    for (Enumeration<NetworkInterface> e = NetworkInterface
            .getNetworkInterfaces(); e.hasMoreElements();) {
        NetworkInterface netIF = e.nextElement();
        for (Enumeration<InetAddress> iadrs = netIF.getInetAddresses(); iadrs
                .hasMoreElements();) {
            InetAddress iadr = iadrs.nextElement();
            if (iadr instanceof Inet6Address) {
                System.err.println("Test NetworkInterface:  " + netIF);
                Inet6Address i6adr = (Inet6Address) iadr;
                System.err.println("Testing with " + iadr);
                System.err.println(" scoped iface: "
                        + i6adr.getScopedInterface());
                testInet6AddressSerialization(i6adr, null);
            }
        }
    }
}
 
private String getIPFromNetworkInterface(String networkInterface) {

		if (!TestConfig.hasValidNetworkInterface) {
			return inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
		}

		try {
			NetworkInterface netInterface = NetworkInterface.getByName(networkInterface);

			Enumeration<InetAddress> inetAddress = netInterface.getInetAddresses();
			while (inetAddress.hasMoreElements()) {
				InetAddress currentAddress = inetAddress.nextElement();
				if (currentAddress instanceof Inet4Address
						&& !currentAddress.isLoopbackAddress()) {
					return currentAddress.getHostAddress();
				}
			}
			return networkInterface;
		}
		catch (Exception e) {
			return networkInterface;
		}
	}
 
源代码16 项目: mongodb-async-driver   文件: MockMongoDBServer.java
/**
 * Creates a new MockMongoDBServer.
 *
 * @throws IOException
 *             On a failure creating the server socket.
 */
public MockMongoDBServer() throws IOException {
    myRunningThreads = new CopyOnWriteArrayList<Thread>();
    myActiveClients = new CopyOnWriteArrayList<Socket>();

    myServerSocket = new ServerSocket();
    myServerSocket.bind(new InetSocketAddress(InetAddress
            .getByName("127.0.0.1"), 0));

    myRunning = false;
}
 
源代码17 项目: gemfirexd-oss   文件: InternalLocator.java
public static LocatorStatusResponse statusLocator(int port, InetAddress bindAddress) throws IOException {
  //final int timeout = (60 * 2 * 1000); // 2 minutes
  final int timeout = Integer.MAX_VALUE; // 2 minutes

  try {
    return (LocatorStatusResponse) TcpClient.requestToServer(bindAddress, port,
        new LocatorStatusRequest(), timeout, true);
  }
  catch (ClassNotFoundException e) {
    throw new RuntimeException(e);
  }
}
 
源代码18 项目: Pix-Art-Messenger   文件: Resolver.java
static Result createDefault(final DNSName hostname, final int port) {
    InetAddress ip = null;
    try {
        ip = InetAddress.getByName(hostname.toString());
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return createDefault(hostname, ip, port);
}
 
源代码19 项目: Bytecoder   文件: SSLSocketImpl.java
/**
 * Constructs an SSL connection to a server at a specified
 * address, and TCP port, using the authentication context
 * provided.
 *
 * This endpoint acts as the client, and may rejoin an existing SSL
 * session if appropriate.
 */
SSLSocketImpl(SSLContextImpl sslContext,
        InetAddress address, int peerPort) throws IOException {
    super();
    this.sslContext = sslContext;
    HandshakeHash handshakeHash = new HandshakeHash();
    this.conContext = new TransportContext(sslContext, this,
            new SSLSocketInputRecord(handshakeHash),
            new SSLSocketOutputRecord(handshakeHash), true);

    SocketAddress socketAddress = new InetSocketAddress(address, peerPort);
    connect(socketAddress, 0);
}
 
源代码20 项目: jdk8u-dev-jdk   文件: SocksProxyVersion.java
public static void main(String[] args) throws Exception {
    if (InetAddress.getLocalHost().isLoopbackAddress()) {
        System.out.println("Test cannot run. getLocalHost returns a loopback address");
        return;
    }
    new SocksProxyVersion();
}
 
@Override
public Socket createSocket(InetAddress addr, int port, InetAddress localHostAddr, int localPort) throws IOException {
    Socket socket = createSocket();
    socket.bind(new InetSocketAddress(localHostAddr, localPort));
    socket.connect(new InetSocketAddress(addr, port));
    return socket;
}
 
源代码22 项目: AndroidWebServ   文件: CommonUtil.java
/**
 * @brief 检查主机端口是否被占用
 * @param host 主机
 * @param port 端口
 * @return true: already in use, false: not.
 * @throws UnknownHostException 
 */
public boolean isPortInUse(String host, int port) throws UnknownHostException {
    boolean flag = false;
    InetAddress theAddress = InetAddress.getByName(host);
    try {
        Socket socket = new Socket(theAddress, port);
        socket.close();
        flag = true;
    } catch (IOException e) {
    }
    return flag;
}
 
@BeforeEach
public void setUp() throws IOException {
    validationHandler = new HTTPTestValidationHandler(10);
    byte[] ipAddr = new byte[]{127, 0, 0, 1};
    InetAddress localhost = InetAddress.getByAddress(ipAddr);
    localServer = ServerBootstrap.bootstrap()
            .setLocalAddress(localhost)
            .setListenerPort(HTTP_PORT)
            .registerHandler("/ckc", validationHandler)
            .create();

    localServer.start();
}
 
源代码24 项目: jdk8u_jdk   文件: SimpleNode.java
/**
 * Build the Inform entries from the syntactic tree.
 */
public void buildInformEntries(Hashtable<InetAddress, Vector<String>> dest) {
    if (children != null) {
        for (int i = 0; i < children.length; ++i) {
            SimpleNode n = (SimpleNode)children[i];
            if (n != null) {
                n.buildInformEntries(dest);
            }
        } /* end of loop */
    }
}
 
源代码25 项目: jfreesane   文件: SaneSessionTest.java
@Before
public void initSession() throws Exception {
  String address = System.getenv("SANE_TEST_SERVER_ADDRESS");
  if (address == null) {
    address = "localhost";
  }
  URI hostAndPort = URI.create("my://" + address);
  this.session =
      SaneSession.withRemoteSane(
          InetAddress.getByName(hostAndPort.getHost()),
          hostAndPort.getPort() == -1 ? 6566 : hostAndPort.getPort());
  session.setPasswordProvider(correctPasswordProvider);
}
 
源代码26 项目: casquatch   文件: CasquatchPodamFactoryImpl.java
/**
 * Extends constructor for default settings
 */
public CasquatchPodamFactoryImpl() {
    super();
    this.getStrategy().addOrReplaceTypeManufacturer(BigDecimal.class, new BigDecimalStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(BigInteger.class, new BigIntegerStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(ByteBuffer.class, new ByteBufferStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(InetAddress.class, new InetAddressStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(Instant.class, new InstantStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(LocalDate.class, new LocalDateStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(LocalTime.class, new LocalTimeStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(UUID.class, new UUIDStrategy());
}
 
源代码27 项目: disconf   文件: MachineInfo.java
/**
 * @return
 *
 * @Description: 获取机器名
 */
public static String getHostName() throws Exception {

    try {
        InetAddress addr = InetAddress.getLocalHost();
        String hostname = addr.getHostName();

        return hostname;

    } catch (UnknownHostException e) {

        throw new Exception(e);
    }
}
 
源代码28 项目: netbeans   文件: MySQLDatabaseServer.java
@Override
public void checkConfiguration() throws DatabaseException {
    // Make sure the host name is a known host name
    try {
        InetAddress.getAllByName(getHost());
    } catch (UnknownHostException ex) {
        synchronized(this) {
            configError = NbBundle.getMessage(MySQLDatabaseServer.class, "MSG_UnknownHost", getHost());
            setState(ServerState.CONFIGERR);
        }
        LOGGER.log(Level.INFO, configError, ex);
        throw new DatabaseException(configError, ex);
    }

    try {
        String port = getPort();
        if (port == null) {
            throw new NumberFormatException();
        }
        Integer.valueOf(port);
    } catch (NumberFormatException nfe) {
        synchronized(this) {
            configError = NbBundle.getMessage(MySQLDatabaseServer.class, "MSG_InvalidPortNumber", getPort());
            setState(ServerState.CONFIGERR);
        }
        LOGGER.log(Level.INFO, configError, nfe);
        throw new DatabaseException(configError, nfe);
    }
}
 
源代码29 项目: T0rlib4Android   文件: Socks5DatagramSocket.java
/**
 * Used by UDPRelayServer.
 */
Socks5DatagramSocket(boolean server_mode, UDPEncapsulation encapsulation,
		InetAddress relayIP, int relayPort) throws IOException {
	super();
	this.server_mode = server_mode;
	this.relayIP = relayIP;
	this.relayPort = relayPort;
	this.encapsulation = encapsulation;
	this.proxy = null;
}
 
源代码30 项目: openjdk-jdk8u-backup   文件: HostAddress.java
private int getAddrType(InetAddress inetAddress) {
    int addressType = 0;
    if (inetAddress instanceof Inet4Address)
        addressType = Krb5.ADDRTYPE_INET;
    else if (inetAddress instanceof Inet6Address)
        addressType = Krb5.ADDRTYPE_INET6;
    return (addressType);
}
 
 类所在包
 同包方法