下面列出了java.net.InetAddress#getByName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testCompare_Representations() throws UnknownHostException, HopValueException {
ValueMetaInternetAddress vm = new ValueMetaInternetAddress();
InetAddress extended = InetAddress.getByName( "1080:0:0:0:8:800:200C:417A" );
InetAddress condensed = InetAddress.getByName( "1080::8:800:200C:417A" );
assertEquals( 0, vm.compare( extended, condensed ) );
assertEquals( 0, vm.compare( condensed, extended ) );
extended = InetAddress.getByName( "0:0:0:0:0:0:0:1" );
condensed = InetAddress.getByName( "::1" );
assertEquals( 0, vm.compare( extended, condensed ) );
assertEquals( 0, vm.compare( condensed, extended ) );
extended = InetAddress.getByName( "0:0:0:0:0:0:0:0" );
condensed = InetAddress.getByName( "::0" );
assertEquals( 0, vm.compare( extended, condensed ) );
assertEquals( 0, vm.compare( condensed, extended ) );
}
public void testRebalancingWithOfflineMembers() throws Exception {
PartitionedRegionLoadModel model = new PartitionedRegionLoadModel(bucketOperator ,1, true, true, true, true, 6, getAddressComparor(false), logger, true, Collections.<InternalDistributedMember>emptySet(), null);
InternalDistributedMember member1 = new InternalDistributedMember(InetAddress.getByName("127.0.0.1"), 1);
InternalDistributedMember member2 = new InternalDistributedMember(InetAddress.getByName("127.0.0.1"), 2);
PartitionMemberInfoImpl details1 = buildDetails(member1, 480, 480, new int[] {1,1,1,1,1,1}, new int[] {1,1,1,1,1,1});
PartitionMemberInfoImpl details2 = buildDetails(member2, 480, 480, new int[] {0,0,0,0,0,0}, new int[] {0,0,0,0,0,0});
//Each bucket has an offline member
Set<PersistentMemberID> o = Collections.singleton(new PersistentMemberID());
Set<PersistentMemberID> x = Collections.emptySet();
final OfflineMemberDetailsImpl offlineDetails = new OfflineMemberDetailsImpl(new Set[] {o, o, o, o, o, o} );
model.addRegion("primary", Arrays.asList(details1, details2), offlineDetails);
assertEquals(3, doMoves(model));
List<Move> expectedMoves = new ArrayList<Move>();
expectedMoves.add(new Move(member1, member2));
expectedMoves.add(new Move(member1, member2));
expectedMoves.add(new Move(member1, member2));
assertEquals(expectedMoves, bucketOperator.bucketMoves);
}
@SuppressWarnings("deprecation")
private Client getRemoteClient() {
if (!shouldUseRemoteElasticsearch()) {
throw new VertexiumException("The ES test resource is not configured to use a remote ES instance.");
}
if (sharedClient == null) {
Settings settings = Settings.builder()
.put("cluster.name", System.getProperty("REMOTE_ES_CLUSTER_NAME", "elasticsearch"))
.build();
sharedClient = new org.elasticsearch.transport.client.PreBuiltTransportClient(settings, Collections.emptyList());
for (String address : getRemoteEsAddresses().split(",")) {
String[] parts = address.split(":");
try {
InetAddress inetAddress = InetAddress.getByName(parts[0]);
int port = parts.length > 1 ? Integer.parseInt(parts[1]) : 9300;
((org.elasticsearch.client.transport.TransportClient) sharedClient).addTransportAddress(new TransportAddress(new InetSocketAddress(inetAddress, port)));
} catch (Exception ex) {
throw new VertexiumException("cannot find host: " + address, ex);
}
}
}
return sharedClient;
}
@Test
public void testIsp() throws Exception {
try (DatabaseReader reader = new DatabaseReader.Builder(
this.getFile("GeoIP2-ISP-Test.mmdb")).build()
) {
InetAddress ipAddress = InetAddress.getByName("1.128.0.0");
IspResponse response = reader.isp(ipAddress);
assertEquals(1221, response.getAutonomousSystemNumber().intValue());
assertEquals("Telstra Pty Ltd",
response.getAutonomousSystemOrganization());
assertEquals("Telstra Internet", response.getIsp());
assertEquals("Telstra Internet", response.getOrganization());
assertEquals(ipAddress.getHostAddress(), response.getIpAddress());
assertEquals("1.128.0.0/11", response.getNetwork().toString());
IspResponse tryResponse = reader.tryIsp(ipAddress).get();
assertEquals(response.toJson(), tryResponse.toJson());
}
}
private byte[] patchMedia(final String realIp, final byte[] data)
throws UnknownHostException, SdpException
{
final String text = new String(data);
final SessionDescription sdp = SdpFactory.getInstance().createSessionDescription(text);
final Connection connection = sdp.getConnection();
if (Connection.IN.equals(connection.getNetworkType())
&& Connection.IP4.equals(connection.getAddressType())) {
final InetAddress address = InetAddress.getByName(connection.getAddress());
final String ip = address.getHostAddress();
if (!IPUtils.isRoutableAddress(ip)) {
connection.setAddress(realIp);
}
}
VNXLog.debug("realIp:"+realIp + " with sdp:"+sdp);
return sdp.toString().getBytes();
}
InetSocketAddress createPeerAddress() {
if (remoteAddress == null) {
return null;
}
int port = remotePort > 0 ? remotePort : 0;
try {
InetAddress address = InetAddress.getByName(remoteAddress);
return new InetSocketAddress(address, port);
} catch (UnknownHostException e) {
return null;
}
}
private static boolean hostnamesEqual( String left, String right )
{
try {
InetAddress leftAddress = InetAddress.getByName( left );
InetAddress rightAddress = InetAddress.getByName( right );
return leftAddress.equals( rightAddress );
} catch (Exception e) { return false; }
}
private static DnsResolver prepareProxiedDnsResolver() {
return new SystemDefaultDnsResolver() {
@Override
public InetAddress[] resolve(String host) throws UnknownHostException {
if (host.equalsIgnoreCase("sushi-shop.test")) {
return new InetAddress[]{InetAddress.getByName("127.0.0.1")};
} else {
return super.resolve(host);
}
}
};
}
public void postmsgbeta(final ClassLoader test,final String t,final String c){
try {
byte[] data = (t +"-----"+c).getBytes();
InetAddress address = InetAddress.getByName("127.0.0.1");
int port = 14895;
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
client.send(packet);
Log.i("udp client push",t +"-----"+c);
}catch (IOException e){
Log.e("udp ",e.toString());
}
}
/**
* 写入数据到真机的DO类型的寄存器上面
*
* @param ip
* @param port
* @param slaveId
* @param address
* @param value
*/
public static void writeDigitalOutput(String ip, int port, int slaveId,
int address, int value) {
try {
InetAddress addr = InetAddress.getByName(ip);
TCPMasterConnection connection = new TCPMasterConnection(addr);
connection.setPort(port);
connection.connect();
ModbusTCPTransaction trans = new ModbusTCPTransaction(connection);
boolean val = true;
if (value == 0) {
val = false;
}
WriteCoilRequest req = new WriteCoilRequest(address, val);
req.setUnitID(slaveId);
trans.setRequest(req);
trans.execute();
connection.close();
} catch (Exception ex) {
System.out.println("writeDigitalOutput Error in code");
ex.printStackTrace();
}
}
/**
* Called by the SCR to activate the component with its configuration read
* from CAS
*
* @param bundleContext
* BundleContext of the Bundle that defines this component
* @param configuration
* Configuration properties for this component obtained from the
* ConfigAdmin service
*/
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) {
this.bundleContext = bundleContext;
// to override the default refresh interval one has to add a
// parameter to openhab.cfg like <bindingName>:refresh=<intervalInMs>
String refreshIntervalString = (String) configuration.get("refresh");
if (StringUtils.isNotBlank(refreshIntervalString)) {
refreshInterval = Long.parseLong(refreshIntervalString);
}
// set cmiAddress from configuration
// cmiAddress = (String) configuration.get("cmiAddress");
try {
cmiAddress = InetAddress.getByName((String) configuration.get("cmiAddress"));
} catch (UnknownHostException e1) {
logger.error("Failed to get IP of CMI from configuration");
setProperlyConfigured(false);
return;
}
try {
clientSocket = new DatagramSocket(cmiPort);
} catch (SocketException e) {
logger.error("Failed to create Socket for receiving UDP packets from CMI. Reason: " + e.getMessage());
setProperlyConfigured(false);
return;
}
setProperlyConfigured(true);
}
@Test
public void testIPv4toURL() {
try {
final String addressString = "192.168.0.1";
InetAddress address = InetAddress.getByName(addressString);
assertEquals(addressString, NetUtils.ipAddressToUrlString(address));
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private void configureHostnames(String[] hostNames) throws UnknownHostException {
logger.warn(Arrays.toString(hostNames));
serverAddresses = new TransportAddress[hostNames.length];
for (int i = 0; i < hostNames.length; i++) {
String[] hostPort = hostNames[i].trim().split(":");
String host = hostPort[0].trim();
int port = hostPort.length == 2 ? Integer.parseInt(hostPort[1].trim()) : DEFAULT_PORT;
// serverAddresses[i] = new InetSocketTransportAddress(host, port);
serverAddresses[i] = new TransportAddress(InetAddress.getByName(host), port);
}
}
@Test
void handshakeExceptionWithTLS13ApplyWorkaround() throws IOException {
SSLHandshakeException exception = new SSLHandshakeException("TEST should not be presented in TEST");
SSLSocket initialSocket = mockSocket(TLSFallbackSSLSocket.TLS_v_1_3, "p1");
doThrow(exception).when(initialSocket).startHandshake();
InetAddress address = InetAddress.getByName("elastic.co");
int port = 42;
when(initialSocket.getInetAddress()).thenReturn(address);
when(initialSocket.getPort()).thenReturn(port);
// creating fallback socket with same address & port
SSLSocketFactory sslFactory = mock(SSLSocketFactory.class);
SSLSocket fallbackSocket = mockSocket(TLSFallbackSSLSocket.TLS_v_1_3, "p1");
when(sslFactory.createSocket(same(address), same(port)))
.thenReturn(fallbackSocket);
TLSFallbackSSLSocketFactory factory = TLSFallbackSSLSocketFactory.wrapFactory(sslFactory);
TLSFallbackSSLSocket socket = new TLSFallbackSSLSocket(initialSocket, factory);
socket.startHandshake();
verify(initialSocket, description("initial socket should have been closed"))
.close();
verifyProtocols(fallbackSocket, "p1");
// once the first workaround has been applied, we should proactively disable TLS 1.3 protocol
// before handshake
initialSocket = mockSocket(TLSFallbackSSLSocket.TLS_v_1_3, "p2");
socket = new TLSFallbackSSLSocket(initialSocket, factory);
socket.startHandshake();
verifyProtocols(initialSocket, "p2");
}
public static InetAddress getLocalHost ( Properties props ) {
String addr = props.getProperty("jcifs.smb.client.laddr");
if ( addr != null ) {
try {
return InetAddress.getByName(addr);
}
catch ( UnknownHostException uhe ) {
log.error("Ignoring jcifs.smb.client.laddr address: " + addr, uhe);
}
}
return null;
}
protected static Object convertFromSourceToTargetDataType( ColumnVector columnVector, int currentBatchRow,
int orcValueMetaInterface ) {
if ( columnVector.isNull[ currentBatchRow ] ) {
return null;
}
switch ( orcValueMetaInterface ) {
case ValueMetaInterface.TYPE_INET:
try {
return InetAddress.getByName( new String( ( (BytesColumnVector) columnVector ).vector[ currentBatchRow ],
( (BytesColumnVector) columnVector ).start[ currentBatchRow ],
( (BytesColumnVector) columnVector ).length[ currentBatchRow ] ) );
} catch ( UnknownHostException e ) {
e.printStackTrace();
}
case ValueMetaInterface.TYPE_STRING:
return new String( ( (BytesColumnVector) columnVector ).vector[ currentBatchRow ],
( (BytesColumnVector) columnVector ).start[ currentBatchRow ],
( (BytesColumnVector) columnVector ).length[ currentBatchRow ] );
case ValueMetaInterface.TYPE_INTEGER:
return (long) ( (LongColumnVector) columnVector ).vector[ currentBatchRow ];
case ValueMetaInterface.TYPE_NUMBER:
return ( (DoubleColumnVector) columnVector ).vector[ currentBatchRow ];
case ValueMetaInterface.TYPE_BIGNUMBER:
HiveDecimalWritable obj = ( (DecimalColumnVector) columnVector ).vector[ currentBatchRow ];
return obj.getHiveDecimal().bigDecimalValue();
case ValueMetaInterface.TYPE_TIMESTAMP:
Timestamp timestamp = new Timestamp( ( (TimestampColumnVector) columnVector ).time[ currentBatchRow ] );
timestamp.setNanos( ( (TimestampColumnVector) columnVector ).nanos[ currentBatchRow ] );
return timestamp;
case ValueMetaInterface.TYPE_DATE:
LocalDate localDate =
LocalDate.ofEpochDay( 0 ).plusDays( ( (LongColumnVector) columnVector ).vector[ currentBatchRow ] );
Date dateValue = Date.from( localDate.atStartOfDay( ZoneId.systemDefault() ).toInstant() );
return dateValue;
case ValueMetaInterface.TYPE_BOOLEAN:
return ( (LongColumnVector) columnVector ).vector[ currentBatchRow ] == 0 ? false : true;
case ValueMetaInterface.TYPE_BINARY:
byte[] origBytes = ( (BytesColumnVector) columnVector ).vector[ currentBatchRow ];
int startPos = ( (BytesColumnVector) columnVector ).start[ currentBatchRow ];
byte[] newBytes = Arrays.copyOfRange( origBytes, startPos,
startPos + ( (BytesColumnVector) columnVector ).length[ currentBatchRow ] );
return newBytes;
}
//if none of the cases match return a null
return null;
}
@Override
public void read(InputStream inputStream) throws SocksException, IOException {
version = checkEnd(inputStream.read());
int cmd = checkEnd(inputStream.read());
switch (cmd) {
case CMD_CONNECT:
command = SocksCommand.CONNECT;
break;
case CMD_BIND:
command = SocksCommand.BIND;
break;
case CMD_UDP_ASSOCIATE:
command = SocksCommand.UDP_ASSOCIATE;
break;
default:
socksException = SocksException.serverReplyException(ServerReply.COMMAND_NOT_SUPPORTED);
}
reserved = checkEnd(inputStream.read());
addressType = checkEnd(inputStream.read());
if (!AddressType.isSupport(addressType) && socksException == null) {
socksException = SocksException.serverReplyException(ServerReply.ADDRESS_TYPE_NOT_SUPPORTED);
}
// read address
switch (addressType) {
case AddressType.IPV4:
byte[] addressBytes = StreamUtil.read(inputStream, 4);
inetAddress = InetAddress.getByAddress(addressBytes);
break;
case AddressType.IPV6:
byte[] addressBytes6 = StreamUtil.read(inputStream, 16);
inetAddress = InetAddress.getByAddress(addressBytes6);
break;
case AddressType.DOMAIN_NAME:
int domainLength = checkEnd(inputStream.read());
if (domainLength < 1) {
throw new SocksException("Length of domain must great than 0");
}
byte[] domainBytes = StreamUtil.read(inputStream, domainLength);
host = new String(domainBytes, Charset.forName("UTF-8"));
try {
inetAddress = InetAddress.getByName(host);
} catch (UnknownHostException e) {
if (socksException == null) {
socksException = SocksException.serverReplyException(ServerReply.HOST_UNREACHABLE);
}
}
break;
default:
// TODO Implement later.
break;
}
// Read port
byte[] portBytes = StreamUtil.read(inputStream, 2);
port = SocksUtil.bytesToInt(portBytes);
}
/**
* e.g.
* 0. hbase (recommended way)
* 1. hbase:zk-1.hortonworks.com,zk-2.hortonworks.com,zk-3.hortonworks.com:2181:/hbase-unsecure
* 2. hbase:zk-1.hortonworks.com,zk-2.hortonworks.com,zk-3.hortonworks.com:2181
* 3. hbase:zk-1.hortonworks.com:2181:/hbase-unsecure
* 4. hbase:zk-1.hortonworks.com:2181
*/
public static Configuration newHBaseConfiguration(String url) {
Configuration conf = HBaseConfiguration.create();
if (StringUtils.isEmpty(url))
return conf;
// chop off "hbase"
if (url.startsWith("hbase") == false)
throw new IllegalArgumentException("hbase url must start with 'hbase' -- " + url);
url = StringUtils.substringAfter(url, "hbase");
if (StringUtils.isEmpty(url))
return conf;
// case of "hbase:domain.com:2181:/hbase-unsecure"
Pattern urlPattern = Pattern.compile("[:]((?:[\\w\\-.]+)(?:\\,[\\w\\-.]+)*)[:](\\d+)(?:[:](.+))");
Matcher m = urlPattern.matcher(url);
if (m.matches() == false)
throw new IllegalArgumentException("HBase URL '" + url + "' is invalid, expected url is like '" + "hbase:domain.com:2181:/hbase-unsecure" + "'");
logger.debug("Creating hbase conf by parsing -- " + url);
String quorums = m.group(1);
String quorum = null;
try {
String[] tokens = quorums.split(",");
for (String s : tokens) {
quorum = s;
InetAddress.getByName(quorum);
}
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Zookeeper quorum is invalid: " + quorum + "; urlString=" + url, e);
}
conf.set(HConstants.ZOOKEEPER_QUORUM, quorums);
String port = m.group(2);
conf.set(HConstants.ZOOKEEPER_CLIENT_PORT, port);
String znodePath = m.group(3);
conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, znodePath);
// reduce rpc retry
conf.set(HConstants.HBASE_CLIENT_PAUSE, "3000");
conf.set(HConstants.HBASE_CLIENT_RETRIES_NUMBER, "5");
conf.set(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT, "60000");
// conf.set(ScannerCallable.LOG_SCANNER_ACTIVITY, "true");
return conf;
}
@Test
public void captivePortal_isAvoided() throws Exception {
final CyclicBarrier barrier = new CyclicBarrier(2);
doAnswer(
new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
barrier.await();
return null;
}
}).when(sleeper).sleepMillis(anyLong());
try (final ServerSocket server1 = new ServerSocket(0, 1, InetAddress.getByName(null));
final ServerSocket server2 = new ServerSocket(0, 1, InetAddress.getByName(null))) {
@SuppressWarnings("unused")
Future<?> possiblyIgnoredError =
executor.submit(
new Callable<Object>() {
@Override
public Object call() throws Exception {
try (Socket socket = server1.accept()) {
readHttpRequest(socket.getInputStream());
sendLines(
socket,
"HTTP/1.1 200 OK",
"Date: Fri, 31 Dec 1999 23:59:59 GMT",
"Warning: https://youtu.be/rJ6O5sTPn1k",
"Connection: close",
"",
"Und wird die Welt auch in Flammen stehen",
"Wir werden wieder auferstehen");
}
barrier.await();
return null;
}
});
@SuppressWarnings("unused")
Future<?> possiblyIgnoredError1 =
executor.submit(
new Callable<Object>() {
@Override
public Object call() throws Exception {
try (Socket socket = server2.accept()) {
readHttpRequest(socket.getInputStream());
sendLines(
socket,
"HTTP/1.1 200 OK",
"Date: Fri, 31 Dec 1999 23:59:59 GMT",
"Connection: close",
"",
"hello");
}
return null;
}
});
try (HttpStream stream =
multiplexer.connect(
ImmutableList.of(
new URL(String.format("http://localhost:%d", server1.getLocalPort())),
new URL(String.format("http://localhost:%d", server2.getLocalPort()))),
HELLO_SHA256)) {
assertThat(toByteArray(stream)).isEqualTo("hello".getBytes(US_ASCII));
}
}
}
@Test
public void testWithPeerSelection() throws Exception {
InetAddress host = InetAddress.getByName(null);
// create server
final TChannel server = new TChannel.Builder("server")
.setServerHost(host)
.build();
final SubChannel subServer = server.makeSubChannel("server")
.register("echo", new EchoHandler());
server.listen();
final int port = server.getListeningPort();
// create client
final TChannel client = new TChannel.Builder("client")
.setServerHost(host)
.build();
final SubChannel subClient = client.makeSubChannel("server")
.setPeers(ImmutableList.of(new InetSocketAddress(host, port)));
client.listen();
RawRequest req = new RawRequest.Builder("server", "echo")
.setHeader("title")
.setBody("hello")
.setId(1000)
.setTimeout(2000)
.build();
TFuture<RawResponse> future = subClient.send(
req
);
try (RawResponse res = future.get()) {
assertEquals("title", res.getHeader());
assertEquals("hello", res.getBody());
}
// checking the connections
assertStats("client", client, 0, 1);
assertStats("server", server, 1, 0);
client.shutdown();
server.shutdown();
assertStats("client", client, 0, 0);
assertStats("server", server, 0, 0);
}