下面列出了java.nio.channels.UnsupportedAddressTypeException#java.net.Inet4Address 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* If {@code ipType} is "internal", returns the internal IP address of the
* current machine. Otherwise, if {@code ipType} is "external", returns the
* external IP address of the current machine.
*
* @param ipType type of IP address to return
* @return either the internal or external IP address of the current machine
* @throws IOException
*/
public static String getIP(String ipType) throws IOException {
String ret = null;
if (ipType.equals("internal")) {
Enumeration<NetworkInterface> majorInterfaces = NetworkInterface.getNetworkInterfaces();
while (majorInterfaces.hasMoreElements()) {
NetworkInterface inter = majorInterfaces.nextElement();
for (Enumeration<InetAddress> minorInterfaces = inter.getInetAddresses(); minorInterfaces
.hasMoreElements(); ) {
InetAddress add = minorInterfaces.nextElement();
if (!add.isLoopbackAddress())
if (add instanceof Inet4Address) {
ret = add.getHostAddress();
break;
}
}
}
} else if (ipType.equals("external")) {
URL checkIP = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(checkIP.openStream()));
String ip = in.readLine();
in.close();
ret = ip;
}
return ret;
}
/**
* Returns a list of all the addresses on the system.
* @param inclLoopback
* if {@code true}, include the loopback addresses
* @param ipv4Only
* it {@code true}, only IPv4 addresses will be included
*/
static List<InetAddress> getAddresses(boolean inclLoopback,
boolean ipv4Only)
throws SocketException {
ArrayList<InetAddress> list = new ArrayList<InetAddress>();
Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netInf : Collections.list(nets)) {
Enumeration<InetAddress> addrs = netInf.getInetAddresses();
for (InetAddress addr : Collections.list(addrs)) {
if (!list.contains(addr) &&
(inclLoopback ? true : !addr.isLoopbackAddress()) &&
(ipv4Only ? (addr instanceof Inet4Address) : true)) {
list.add(addr);
}
}
}
return list;
}
public InetAddress[] lookupAllHostAddr( String name )
throws UnknownHostException
{
String log = "[CDNS] Lookup request";
String ip = NAMES.get( name );
InetAddress[] result = new InetAddress[ 0 ];
if ( ip != null && ip.length() > 0 ) {
log += " on managed name (" + name + ")";
byte[] ipBytes = ipStringToBytes( ip );
result = new InetAddress[]{ Inet4Address.getByAddress( ipBytes ) };
} else {
log += " on non-managed name (" + name + ")";
result = DEFAULT_DNS.lookupAllHostAddr( name );
}
return result;
}
@Override
public int compare(final Inet4Address aa, final Inet4Address ba) {
final byte[] a = aa.getAddress();
final byte[] b = ba.getAddress();
// local subnet comes after all else.
if (a[0] == 127 && b[0] != 127) {
return 1;
}
if (a[0] != 127 && b[0] == 127) {
return -1;
}
for (int i = 0; i < 4; i++) {
if (a[i] < b[i]) {
return -1;
}
if (a[i] > b[i]) {
return 1;
}
}
return 0;
}
/**
* get server ip.
*
* @return
*/
public static String getCurrentIp() {
try {
Enumeration<NetworkInterface> networkInterfaces =
NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = networkInterfaces.nextElement();
Enumeration<InetAddress> nias = ni.getInetAddresses();
while (nias.hasMoreElements()) {
InetAddress ia = nias.nextElement();
if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress()
&& ia instanceof Inet4Address) {
return ia.getHostAddress();
}
}
}
} catch (SocketException e) {
log.error("getCurrentIp error.");
}
return null;
}
@Override
public InetAddress address(String inetHost, ResolvedAddressTypes resolvedAddressTypes) {
String normalized = normalize(inetHost);
switch (resolvedAddressTypes) {
case IPV4_ONLY:
return inet4Entries.get(normalized);
case IPV6_ONLY:
return inet6Entries.get(normalized);
case IPV4_PREFERRED:
Inet4Address inet4Address = inet4Entries.get(normalized);
return inet4Address != null? inet4Address : inet6Entries.get(normalized);
case IPV6_PREFERRED:
Inet6Address inet6Address = inet6Entries.get(normalized);
return inet6Address != null? inet6Address : inet4Entries.get(normalized);
default:
throw new IllegalArgumentException("Unknown ResolvedAddressTypes " + resolvedAddressTypes);
}
}
@Test
public void testInterfacesetAddress() throws libc.ErrnoException, UnknownHostException {
libc.sockaddr_in originalAddress= linuxutils.ioctl_SIOCGIFADDR(device);
logger.info("original {}", originalAddress);
InetAddress ipv4= Inet4Address.getByName("127.0.0.4");
libc.sockaddr_in address= new libc.sockaddr_in(ipv4);
linuxutils.ioctl_SIOCSIFADDR(device,address);
address= linuxutils.ioctl_SIOCGIFADDR(device);
logger.info("IPv4 sockaddr_in: {}", Hexdump.bytesToHex(address.array(), address.array().length));
logger.info("{}", address);
Assert.assertEquals(0, address.port);
Assert.assertEquals(0x7f000004, address.address);
Assert.assertEquals(0x02,address.family);
logger.info("{}", address.toInetAddress());
logger.info("{}", address.toInetSocketAddress());
linuxutils.ioctl_SIOCSIFADDR(device,new libc.sockaddr_in(0x7f000003,(short)0,socket.AF_INET));
}
private static Inet4Address getInterfaceAddress(WifiP2pGroup info) {
NetworkInterface iface;
try {
iface = NetworkInterface.getByName(info.getInterface());
} catch (SocketException ex) {
Slog.w(TAG, "Could not obtain address of network interface "
+ info.getInterface(), ex);
return null;
}
Enumeration<InetAddress> addrs = iface.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress addr = addrs.nextElement();
if (addr instanceof Inet4Address) {
return (Inet4Address)addr;
}
}
Slog.w(TAG, "Could not obtain address of network interface "
+ info.getInterface() + " because it had no IPv4 addresses.");
return null;
}
public static Set<String> getLocalIps() throws SocketException
{
Set<String> localIps = Sets.newHashSet();
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
while ( netInterfaces.hasMoreElements() )
{
NetworkInterface networkInterface = netInterfaces.nextElement();
Enumeration<InetAddress> addressEnumeration = networkInterface.getInetAddresses();
while ( addressEnumeration.hasMoreElements() )
{
InetAddress address = addressEnumeration.nextElement();
if ( address instanceof Inet4Address )
{
localIps.add( address.getHostAddress() );
}
}
}
return localIps;
}
public static String getServerIpAddr() {
if(ResourceUtils.containsProperty("spring.cloud.client.ipAddress")){
return ResourceUtils.getProperty("spring.cloud.client.ipAddress");
}
if(serverIpAddr != null)return serverIpAddr;
try {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
outter:while (en.hasMoreElements()) {
NetworkInterface i = en.nextElement();
for (Enumeration<InetAddress> en2 = i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr = en2.nextElement();
if (!addr.isLoopbackAddress()) {
if (addr instanceof Inet4Address) {
serverIpAddr = addr.getHostAddress();
break outter;
}
}
}
}
} catch (Exception e) {
serverIpAddr = UNKNOW;
}
return serverIpAddr;
}
TCPTun(CapEnv capEnv,
Inet4Address serverAddress, short serverPort,
MacAddress srcAddress_mac, MacAddress dstAddrress_mac) {
this.capEnv = capEnv;
sendHandle = capEnv.sendHandle;
this.remoteAddress = serverAddress;
this.remotePort = serverPort;
localAddress = capEnv.local_ipv4;
localPort = (short) (random.nextInt(64 * 1024 - 1 - 10000) + 10000);
Packet syncPacket = null;
try {
syncPacket = PacketUtils.createSync(srcAddress_mac, dstAddrress_mac, localAddress, localPort,
serverAddress, serverPort, localStartSequence, getIdent());
try {
sendHandle.sendPacket(syncPacket);
localSequence = localStartSequence + 1;
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
MLog.println("发送第一次握手 " + " ident " + localIdent);
MLog.println("" + syncPacket);
}
/**
* Returns a list of all the addresses on the system.
* @param inclLoopback
* if {@code true}, include the loopback addresses
* @param ipv4Only
* it {@code true}, only IPv4 addresses will be included
*/
static List<InetAddress> getAddresses(boolean inclLoopback,
boolean ipv4Only)
throws SocketException {
ArrayList<InetAddress> list = new ArrayList<InetAddress>();
Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netInf : Collections.list(nets)) {
Enumeration<InetAddress> addrs = netInf.getInetAddresses();
for (InetAddress addr : Collections.list(addrs)) {
if (!list.contains(addr) &&
(inclLoopback ? true : !addr.isLoopbackAddress()) &&
(ipv4Only ? (addr instanceof Inet4Address) : true)) {
list.add(addr);
}
}
}
return list;
}
@Override
public DHTPluginContact
importContact(
InetSocketAddress address,
byte version )
{
if ( !isEnabled()){
throw( new RuntimeException( "DHT isn't enabled" ));
}
InetAddress contact_address = address.getAddress();
for ( DHTPluginImpl dht: dhts ){
InetAddress dht_address = dht.getLocalAddress().getAddress().getAddress();
if ( ( contact_address instanceof Inet4Address && dht_address instanceof Inet4Address ) ||
( contact_address instanceof Inet6Address && dht_address instanceof Inet6Address )){
return( dht.importContact( address, version ));
}
}
return( null );
}
/**
* Test method for {@link com.digi.xbee.api.IPDevice#readIPDataPacket(Inet4Address, int))}.
*
* @throws Exception
*/
@Test
public final void testReadIPDataPacketNotIPTimeout() throws Exception {
// Setup the resources for the test.
Mockito.doAnswer(new Answer<XBeePacket>() {
public XBeePacket answer(InvocationOnMock invocation) throws Exception {
return null;
}
}).when(mockXBeePacketsQueue).getFirstIPDataPacket(Mockito.anyInt());
// Call the method under test.
IPMessage message = Whitebox.invokeMethod(ipDevice, "readIPDataPacket", (Inet4Address)null, 100);
// Verify the result.
assertThat("Message must be null", message, is(equalTo(null)));
Mockito.verify(mockXBeePacketsQueue).getFirstIPDataPacket(100);
}
@Override
public void start(Collection<DHT> dhts, ConfigReader config) {
try {
channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, 1);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
// we only need to send, not to receive, so need to bind to a specific port
channel.bind(new InetSocketAddress(0));
channel.connect(new InetSocketAddress(InetAddress.getByAddress(new byte[] {(byte) 224,0,23,5}), 9696));
} catch (IOException e) {
e.printStackTrace();
return;
}
t.setDaemon(true);
t.setName("opentracker-sync");
t.start();
// OT-sync only supports ipv4 atm
dhts.stream().filter(d -> d.getType().PREFERRED_ADDRESS_TYPE == Inet4Address.class).forEach(d -> {
d.addIncomingMessageListener(this::incomingPacket);
});
}
/**
* Returns a list of all the addresses on the system.
* @param inclLoopback
* if {@code true}, include the loopback addresses
* @param ipv4Only
* it {@code true}, only IPv4 addresses will be included
*/
static List<InetAddress> getAddresses(boolean inclLoopback,
boolean ipv4Only)
throws SocketException {
ArrayList<InetAddress> list = new ArrayList<InetAddress>();
Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netInf : Collections.list(nets)) {
Enumeration<InetAddress> addrs = netInf.getInetAddresses();
for (InetAddress addr : Collections.list(addrs)) {
if (!list.contains(addr) &&
(inclLoopback ? true : !addr.isLoopbackAddress()) &&
(ipv4Only ? (addr instanceof Inet4Address) : true)) {
list.add(addr);
}
}
}
return list;
}
/**
* 获取ip地址方法
* @return
*/
public static String GetHostIp() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr
.hasMoreElements();) {
InetAddress inetAddress = ipAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
//if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet6Address) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
} catch (Exception e) {
}
return null;
}
public static List<Inet4Address> getLocalIp4AddressFromNetworkInterface() throws SocketException {
List<Inet4Address> addresses = new ArrayList<>(1);
Enumeration e = NetworkInterface.getNetworkInterfaces();
if (e == null) {
return addresses;
}
while (e.hasMoreElements()) {
NetworkInterface n = (NetworkInterface) e.nextElement();
if (!isValidInterface(n)) {
continue;
}
Enumeration ee = n.getInetAddresses();
while (ee.hasMoreElements()) {
InetAddress i = (InetAddress) ee.nextElement();
if (isValidAddress(i)) {
addresses.add((Inet4Address) i);
}
}
}
return addresses;
}
@Override
protected NetworkAddressFactory createNetworkAddressFactory(int streamListenPort) {
// We are only interested in 127.0.0.1
return new NetworkAddressFactoryImpl(streamListenPort) {
@Override
protected boolean isUsableNetworkInterface(NetworkInterface iface) throws Exception {
return (iface.isLoopback());
}
@Override
protected boolean isUsableAddress(NetworkInterface networkInterface, InetAddress address) {
return (address.isLoopbackAddress() && address instanceof Inet4Address);
}
};
}
/**
* Constructs a new test instance manager
*/
public TestInstanceManager() {
final HardwareDescription hd = HardwareDescriptionFactory.construct(1, 1L, 1L);
final InstanceTypeDescription itd = InstanceTypeDescriptionFactory.construct(INSTANCE_TYPE, hd, 1);
instanceMap.put(INSTANCE_TYPE, itd);
this.allocatedResources = new ArrayList<AllocatedResource>();
try {
final InstanceConnectionInfo ici = new InstanceConnectionInfo(Inet4Address.getLocalHost(), 1, 1);
final NetworkTopology nt = new NetworkTopology();
final TestInstance ti = new TestInstance(INSTANCE_TYPE, ici, nt.getRootNode(), nt, hd);
this.allocatedResources.add(new AllocatedResource(ti, INSTANCE_TYPE, new AllocationID()));
} catch (UnknownHostException e) {
throw new RuntimeException(StringUtils.stringifyException(e));
}
}
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;
}
@Test
public void testParse() throws IOException {
String hostsString = new StringBuilder()
.append("127.0.0.1 host1").append("\n") // single hostname, separated with blanks
.append("::1 host1").append("\n") // same as above, but IPv6
.append("\n") // empty line
.append("192.168.0.1\thost2").append("\n") // single hostname, separated with tabs
.append("#comment").append("\n") // comment at the beginning of the line
.append(" #comment ").append("\n") // comment in the middle of the line
.append("192.168.0.2 host3 #comment").append("\n") // comment after hostname
.append("192.168.0.3 host4 host5 host6").append("\n") // multiple aliases
.append("192.168.0.4 host4").append("\n") // host mapped to a second address, must be ignored
.append("192.168.0.5 HOST7").append("\n") // uppercase host, should match lowercase host
.append("192.168.0.6 host7").append("\n") // should be ignored since we have the uppercase host already
.toString();
HostsFileEntries entries = HostsFileParser.parse(new BufferedReader(new StringReader(hostsString)));
Map<String, Inet4Address> inet4Entries = entries.inet4Entries();
Map<String, Inet6Address> inet6Entries = entries.inet6Entries();
assertEquals("Expected 7 IPv4 entries", 7, inet4Entries.size());
assertEquals("Expected 1 IPv6 entries", 1, inet6Entries.size());
assertEquals("127.0.0.1", inet4Entries.get("host1").getHostAddress());
assertEquals("192.168.0.1", inet4Entries.get("host2").getHostAddress());
assertEquals("192.168.0.2", inet4Entries.get("host3").getHostAddress());
assertEquals("192.168.0.3", inet4Entries.get("host4").getHostAddress());
assertEquals("192.168.0.3", inet4Entries.get("host5").getHostAddress());
assertEquals("192.168.0.3", inet4Entries.get("host6").getHostAddress());
assertNotNull("uppercase host doesn't resolve", inet4Entries.get("host7"));
assertEquals("192.168.0.5", inet4Entries.get("host7").getHostAddress());
assertEquals("0:0:0:0:0:0:0:1", inet6Entries.get("host1").getHostAddress());
}
private Ip4SubnetFilterRule(Inet4Address ipAddress, int cidrPrefix, IpFilterRuleType ruleType) {
if (cidrPrefix < 0 || cidrPrefix > 32) {
throw new IllegalArgumentException(String.format("IPv4 requires the subnet prefix to be in range of " +
"[0,32]. The prefix was: %d", cidrPrefix));
}
subnetMask = prefixToSubnetMask(cidrPrefix);
networkAddress = ipToInt(ipAddress) & subnetMask;
this.ruleType = ruleType;
}
@Test
public void testListenInterface() throws Exception
{
Config testConfig = DatabaseDescriptor.loadConfig();
testConfig.listen_interface = suitableInterface.getName();
testConfig.listen_address = null;
DatabaseDescriptor.applyAddressConfig(testConfig);
/*
* Confirm ability to select between IPv4 and IPv6
*/
if (hasIPv4andIPv6)
{
testConfig = DatabaseDescriptor.loadConfig();
testConfig.listen_interface = suitableInterface.getName();
testConfig.listen_address = null;
testConfig.listen_interface_prefer_ipv6 = true;
DatabaseDescriptor.applyAddressConfig(testConfig);
assertEquals(DatabaseDescriptor.getListenAddress().getClass(), Inet6Address.class);
testConfig = DatabaseDescriptor.loadConfig();
testConfig.listen_interface = suitableInterface.getName();
testConfig.listen_address = null;
testConfig.listen_interface_prefer_ipv6 = false;
DatabaseDescriptor.applyAddressConfig(testConfig);
assertEquals(DatabaseDescriptor.getListenAddress().getClass(), Inet4Address.class);
}
else
{
/*
* Confirm first address of interface is selected
*/
assertEquals(DatabaseDescriptor.getRpcAddress(), suitableInterface.getInetAddresses().nextElement());
}
}
private int getAddrType(InetAddress addr) {
int addressType = CHANNEL_BINDING_AF_NULL_ADDR;
if (addr instanceof Inet4Address)
addressType = CHANNEL_BINDING_AF_INET;
else if (addr instanceof Inet6Address)
addressType = CHANNEL_BINDING_AF_INET6;
return (addressType);
}
@Override
public ServiceInfo getServiceInfo(boolean persistent) {
ServiceInfoImpl info = (ServiceInfoImpl) super.getServiceInfo(persistent);
info.addAddress((Inet4Address) _addr);
return info;
}
public static void main(String args[]) throws Exception {
ListeningConnector connector = (ListeningConnector)findConnector("com.sun.jdi.SocketListen");
// check wildcard address
check(connector, (InetAddress)null);
// iterate over all IPv4 addresses and check that binding to
// that address results in the correct result from startListening(Map)
Enumeration nifs = NetworkInterface.getNetworkInterfaces();
while (nifs.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface)nifs.nextElement();
Enumeration addrs = ni.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress addr = (InetAddress)addrs.nextElement();
// JPDA implementation only currently supports IPv4
if (!(addr instanceof Inet4Address)) {
continue;
}
check(connector, addr);
}
}
if (failures > 0) {
throw new RuntimeException(failures + " test(s) failed - see output for details.");
}
}
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);
}
@Override
public InetAddress getLocalAddress(NetworkInterface networkInterface, boolean isIPv6, InetAddress remoteAddress) {
// TODO: This is totally random because we can't access low level InterfaceAddress on Android!
for (InetAddress localAddress : getInetAddresses(networkInterface)) {
if (isIPv6 && localAddress instanceof Inet6Address)
return localAddress;
if (!isIPv6 && localAddress instanceof Inet4Address)
return localAddress;
}
throw new IllegalStateException("Can't find any IPv4 or IPv6 address on interface: " + networkInterface.getDisplayName());
}
private boolean isIPVersionDisabled(Class<? extends InetAddress> type) {
long disabled = configReader.getLong("//core/disableIPVersion").orElse(-1L);
if(disabled == 6 && type.isAssignableFrom(Inet6Address.class))
return true;
if(disabled == 4 && type.isAssignableFrom(Inet4Address.class))
return true;
return false;
}