Java Code Examples for java.net.Inet4Address#getByName()

The following examples show how to use java.net.Inet4Address#getByName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LPWANDeviceTest.java    From xbee-java with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.LPWANDevice#sendIPData(Inet4Address, int, IPProtocol, boolean, byte[])}.
 * 
 * <p>Verify that the method calls the super implementation.</p>
 * 
 * @throws Exception
 */
@SuppressWarnings("deprecation")
@Test
public void testSendIPDataAsyncDeprecated() throws Exception {
	// Do nothing when the sendIPDataAsync of NBIoTDevice is called.
	Mockito.doNothing().when(lpWanDevice).sendIPDataAsync(Mockito.any(Inet4Address.class), 
			Mockito.anyInt(), Mockito.any(IPProtocol.class), Mockito.any(byte[].class));
	
	Inet4Address destAddr = (Inet4Address)Inet4Address.getByName("192.168.1.55");
	int port = 3000;
	IPProtocol protocol = IPProtocol.UDP;
	byte[] data = "Test".getBytes();
	
	// Call the method that should throw the exception.
	lpWanDevice.sendIPDataAsync(destAddr, port, protocol, false, data);
	
	// Verify that the super method was called.
	Mockito.verify(lpWanDevice, Mockito.times(1)).sendIPDataAsync(Mockito.eq(destAddr), 
			Mockito.eq(port), Mockito.eq(protocol), Mockito.eq(data));
}
 
Example 2
Source File: FileTEDBUpdater.java    From netphony-topology with Apache License 2.0 6 votes vote down vote up
public static Inet4Address readNetworkDomain(String fileName) {
	Logger log = LoggerFactory.getLogger("BGP4Peer");
	File file = new File(fileName);
	try {
		DocumentBuilder builder = DocumentBuilderFactory.newInstance()
				.newDocumentBuilder();
		Document doc = builder.parse(file);

		NodeList nodes_domains = doc.getElementsByTagName("domain");
		Element element_domain = (Element) nodes_domains.item(0);
		NodeList nodes_domain_id = element_domain.getElementsByTagName("domain_id");
		Element domain_id_e = (Element) nodes_domain_id.item(0);
		String domain_id = getCharacterDataFromElement(domain_id_e);
		log.info("Network domain: " + domain_id);
		Inet4Address domId = (Inet4Address) Inet4Address
				.getByName(domain_id);
		return domId;
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 3
Source File: InterfaceTest.java    From JavaLinuxNet with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 4
Source File: SendTopology.java    From netphony-topology with Apache License 2.0 6 votes vote down vote up
public void configure( Hashtable<String,TEDB> intraTEDBs,BGP4SessionsInformation bgp4SessionsInformation,boolean sendTopology,int instanceId,boolean sendIntraDomainLinks, MultiDomainTEDB multiTED){
	this.intraTEDBs=intraTEDBs;
	this.bgp4SessionsInformation=bgp4SessionsInformation;
	this.sendTopology= sendTopology;
	this.instanceId = instanceId;
	this.sendIntraDomainLinks=sendIntraDomainLinks;
	this.multiDomainTEDB=multiTED;
	try {
		this.localAreaID=(Inet4Address)Inet4Address.getByName("0.0.0.0");
		this.localBGPLSIdentifer=(Inet4Address)Inet4Address.getByName("1.1.1.1");
	} catch (UnknownHostException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
}
 
Example 5
Source File: Inet4AddressConverter.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
    String hostSlashAddress = reader.getValue();
    int i = hostSlashAddress.indexOf('/');
    try {
        if (i==-1) {
            return Inet4Address.getByName(hostSlashAddress);
        } else {
            String host = hostSlashAddress.substring(0, i);
            String addrS = hostSlashAddress.substring(i+1);
            byte[] addr = new byte[4];
            String[] addrSI = addrS.split("\\.");
            for (int k=0; k<4; k++) addr[k] = (byte)(int)Integer.valueOf(addrSI[k]);
            return Inet4Address.getByAddress(host, addr);
        }
    } catch (UnknownHostException e) {
        throw Exceptions.propagate(e);
    }
}
 
Example 6
Source File: LPWANDeviceTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.LPWANDevice#sendIPDataAsync(java.net.Inet4Address, int, com.digi.xbee.api.models.IPProtocol, byte[])}.
 * 
 * <p>Verify that the method throws an {@code IllegalArgumentException} if
 * the protocol is not UDP.</p>
 * 
 * @throws Exception
 */
@Test
public void testSendIPDataAsyncNotUDP() throws Exception {
	exception.expect(IllegalArgumentException.class);
	exception.expectMessage(is(equalTo("This protocol only supports UDP transmissions.")));
	
	Inet4Address destAddr = (Inet4Address)Inet4Address.getByName("192.168.1.55");
	int port = 3000;
	IPProtocol protocol = IPProtocol.TCP;
	byte[] data = "Test".getBytes();
	
	// Call the method that should throw the exception.
	lpWanDevice.sendIPDataAsync(destAddr, port, protocol, data);
}
 
Example 7
Source File: FileTEDBUpdater.java    From netphony-topology with Apache License 2.0 5 votes vote down vote up
public static Hashtable <Object,Object> getITSites(String fileName){
	Hashtable <Object,Object> it_site_id_domain_ed=new Hashtable <Object,Object>();

	File file2 = new File(fileName);
	try {
		DocumentBuilder builder2 =	DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc2 = builder2.parse(file2);

		NodeList nodes_domains = doc2.getElementsByTagName("domain");

		for (int j = 0; j < nodes_domains.getLength(); j++) {
			Element element_domain = (Element) nodes_domains.item(j);
			NodeList nodes_domain_id =  element_domain.getElementsByTagName("domain_id");
			Element domain_id_e = (Element) nodes_domain_id.item(0);
			String domain_id_str=getCharacterDataFromElement(domain_id_e);
			Inet4Address domain_id= (Inet4Address) Inet4Address.getByName(domain_id_str);

			NodeList ITsites = element_domain.getElementsByTagName("it_site");
			for (int i = 0; i < ITsites.getLength(); i++) {
				Element element = (Element) ITsites.item(i);
				NodeList it_site_id_node = element.getElementsByTagName("it_site_id");
				Element it_site_id_e = (Element) it_site_id_node.item(0);
				String it_site_id=getCharacterDataFromElement(it_site_id_e);
				Inet4Address it_site_id_addr= (Inet4Address) Inet4Address.getByName(it_site_id);

				NodeList domain_id_node = element.getElementsByTagName("domain_id");
				it_site_id_domain_ed.put(it_site_id_addr, domain_id);
				//graph.addVertex(router_id_addr);					
			}

		}

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

	return it_site_id_domain_ed;

}
 
Example 8
Source File: RemoteATCommandWifiPacketTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.packet.wifi.RemoteATCommandWifiPacket#isBroadcast()}.
 *
 * <p>Test the is broadcast method.</p>
 *
 * @throws Exception
 */
@Test
public final void testIsBroadcastTrue() throws Exception {
	// Set up the resources for the test.
	destAddress = (Inet4Address) Inet4Address.getByName(IPDevice.BROADCAST_IP);

	RemoteATCommandWifiPacket packet = new RemoteATCommandWifiPacket(frameID, destAddress, transmitOptions, command, parameter);

	// Call the method under test and verify the result.
	assertThat("Packet should be broadcast", packet.isBroadcast(), is(equalTo(true)));
}
 
Example 9
Source File: DomainIDTLV.java    From netphony-network-protocols with Apache License 2.0 5 votes vote down vote up
public DomainIDTLV(){
	this.TLVType=ObjectParameters.PCEP_TLV_DOMAIN_ID_TLV;
	try {
		domainType=1;//Default value
		domainId=(Inet4Address) Inet4Address.getByName("0.0.0.1");
	} catch (UnknownHostException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 10
Source File: LPWANDeviceTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.LPWANDevice#sendIPData(java.net.Inet4Address, int, com.digi.xbee.api.models.IPProtocol, byte[])}.
 * 
 * <p>Verify that the method throws an {@code IllegalArgumentException} if
 * the protocol is not UDP.</p>
 * 
 * @throws Exception
 */
@Test
public void testSendIPDataNotUDP() throws Exception {
	exception.expect(IllegalArgumentException.class);
	exception.expectMessage(is(equalTo("This protocol only supports UDP transmissions.")));
	
	Inet4Address destAddr = (Inet4Address)Inet4Address.getByName("192.168.1.55");
	int port = 3000;
	IPProtocol protocol = IPProtocol.TCP;
	byte[] data = "Test".getBytes();
	
	// Call the method that should throw the exception.
	lpWanDevice.sendIPData(destAddr, port, protocol, data);
}
 
Example 11
Source File: SendIPDataAsyncTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
	ipAddress = (Inet4Address) Inet4Address.getByName(IP_ADDRESS);
	
	// Instantiate a IPDevice object with a mocked interface.
	ipDevice = PowerMockito.spy(new IPDevice(Mockito.mock(SerialPortRxTx.class)));
	
	// Mock TX IPv4 packet.
	txIPv4Packet = Mockito.mock(TXIPv4Packet.class);
	
	// Whenever a TXIPv4Packet class is instantiated, the mocked txIPv4Packet packet should be returned.
	PowerMockito.whenNew(TXIPv4Packet.class).withAnyArguments().thenReturn(txIPv4Packet);
}
 
Example 12
Source File: Inet.java    From hibernate-types with Apache License 2.0 5 votes vote down vote up
public InetAddress toInetAddress() {
    try {
        String host = address.replaceAll("\\/.*$", "");
        return Inet4Address.getByName(host);
    } catch (UnknownHostException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 13
Source File: Inet.java    From hibernate-types with Apache License 2.0 5 votes vote down vote up
public InetAddress toInetAddress() {
    try {
        String host = address.replaceAll("\\/.*$", "");
        return Inet4Address.getByName(host);
    } catch (UnknownHostException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 14
Source File: SendIPDataTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
	ipAddress = (Inet4Address) Inet4Address.getByName(IP_ADDRESS);
	
	// Instantiate a IPDevice object with a mocked interface.
	ipDevice = PowerMockito.spy(new IPDevice(Mockito.mock(SerialPortRxTx.class)));
	
	// Mock TX IPv4 packet.
	txIPv4Packet = Mockito.mock(TXIPv4Packet.class);
	
	// Whenever a TXIPv4Packet class is instantiated, the mocked txIPv4Packet packet should be returned.
	PowerMockito.whenNew(TXIPv4Packet.class).withAnyArguments().thenReturn(txIPv4Packet);
}
 
Example 15
Source File: Inet.java    From hibernate-types with Apache License 2.0 5 votes vote down vote up
public InetAddress toInetAddress() {
    try {
        String host = address.replaceAll("\\/.*$", "");
        return Inet4Address.getByName(host);
    } catch (UnknownHostException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 16
Source File: FileTEDBUpdater.java    From netphony-topology with Apache License 2.0 4 votes vote down vote up
public static Hashtable<StorageTLV,Object> getStorageCharacteristics(String fileName){
	Hashtable <StorageTLV,Object> storage_site_ed=new Hashtable <StorageTLV,Object>();
	//		StorageTLV storagetlv = new StorageTLV();
	//		ResourceIDSubTLV resourceidsubtlv = new ResourceIDSubTLV();
	//		CostSubTLV costsubtlv = new CostSubTLV();
	//		LinkedList<CostSubTLV> costlist = new LinkedList<CostSubTLV> (); 
	//		StorageSizeSubTLV storagesizesubtlv = new StorageSizeSubTLV();

	File file2 = new File(fileName);
	try {
		DocumentBuilder builder2 =	DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc2 = builder2.parse(file2);

		NodeList nodes_domains = doc2.getElementsByTagName("domain");

		for (int j = 0; j < nodes_domains.getLength(); j++) {
			Element element_domain = (Element) nodes_domains.item(j);
			NodeList nodes_domain_id =  element_domain.getElementsByTagName("domain_id");
			Element domain_id_e = (Element) nodes_domain_id.item(0);
			String domain_id_str=getCharacterDataFromElement(domain_id_e);
			Inet4Address domain_id= (Inet4Address) Inet4Address.getByName(domain_id_str);

			NodeList storages = element_domain.getElementsByTagName("storage");
			for (int i = 0; i < storages.getLength(); i++) {
				StorageTLV storagetlv = new StorageTLV();
				ResourceIDSubTLV resourceidsubtlv = new ResourceIDSubTLV();
				CostSubTLV costsubtlv = new CostSubTLV();
				LinkedList<CostSubTLV> costlist = new LinkedList<CostSubTLV> (); 
				StorageSizeSubTLV storagesizesubtlv = new StorageSizeSubTLV();


				Element element = (Element) storages.item(i);
				NodeList resource_id_node = element.getElementsByTagName("resource_id");
				Element resource_id_e = (Element) resource_id_node.item(0);
				String resource_id=getCharacterDataFromElement(resource_id_e);
				Inet4Address resource_id_addr= (Inet4Address) Inet4Address.getByName(resource_id);

				resourceidsubtlv.setResourceID(resource_id_addr);

				Inet4Address virtual_TI_site= (Inet4Address) Inet4Address.getByName((element.getAttributeNode("it_site").getValue()).toString());
				costsubtlv.setUsageUnit((element.getAttributeNode("UsageUnit").getValue()).getBytes());
				costsubtlv.setUnitaryPrice((element.getAttributeNode("UnitaryPrice").getValue()).getBytes());
				costlist.add(costsubtlv);
				storagesizesubtlv.setTotalSize(Integer.parseInt(element.getAttributeNode("TotalSize").getValue()));
				storagesizesubtlv.setAvailableSize(Integer.parseInt(element.getAttributeNode("AvailableSize").getValue()));

				storagetlv.setResourceIDSubTLV(resourceidsubtlv);
				storagetlv.setCostList(costlist);
				storagetlv.setStorageSizeSubTLV(storagesizesubtlv);

				storage_site_ed.put(storagetlv, virtual_TI_site);					
			}
		}
	}
	catch (Exception e) {
		e.printStackTrace();
	}		 
	return storage_site_ed;
}
 
Example 17
Source File: IPMessageTest.java    From xbee-java with Mozilla Public License 2.0 4 votes vote down vote up
@BeforeClass
public static void setupOnce() throws Exception {
	ipAddress = (Inet4Address) Inet4Address.getByName(IP_ADDRESS);
	ipv6Address = (Inet6Address) Inet6Address.getByName(IPV6_ADDRESS);
}
 
Example 18
Source File: UdpClient.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
public void run()
{
	try
	{
		DatagramSocket datagramSocket = new DatagramSocket(0/*(int) UdpTest.SERVER_PORT + 1*/, Inet4Address.getByName(UdpTest.SERVER_HOST));
		//DatagramSocket datagramSocket = new DatagramSocket(null); // null->unbound
		System.out.println("UdpClient: client ready");

		boolean connect = false; // true ; "connect�" ou non 

		byte[] data = new byte[(int)UdpTest.MSG_SIZE];

		for(int i=0; i<data.length; i++)
		{
			data[i] = (byte)i;// 0;
		}

		DatagramPacket datagramPacket = new DatagramPacket(data,data.length,Inet4Address.getByName(UdpTest.SERVER_HOST),(int) UdpTest.SERVER_PORT); 
		//DatagramPacket datagramPacket = new DatagramPacket(data,data.length,Inet4Address.getByName(UdpTest.SERVER_HOST),3333);
		//DatagramPacket datagramPacket = new DatagramPacket(data,data.length);
		
		System.out.println("UdpClient: data initialized");
		
		if (connect){
			datagramSocket.connect(Inet4Address.getByName(UdpTest.SERVER_HOST),(int) UdpTest.SERVER_PORT);	
			if (datagramSocket.isConnected()) System.out.println("UdpClient: datagramSocket connected");
		}
		
		UdpTest.start = System.currentTimeMillis();
					
		//for(int i=0; i<UdpTest.MSG_NUMBER; i++)
		{

			//System.out.println( "sending: " + i);

			//for(int j=0; j<data.length; j++)
			//	System.out.print(datagramPacket.getData()[j]+", ");
			//System.out.println( "");

			System.out.println("client: localport :"+datagramSocket.getLocalPort());
			datagramSocket.send(datagramPacket);	// le send
			System.out.println("client: localport :"+datagramSocket.getLocalPort());

			if(datagramPacket.getLength() != UdpTest.MSG_SIZE)
				System.out.println(datagramPacket.getLength() + " != " +UdpTest.MSG_SIZE);

			UdpTest.total_sent ++;
		}
		
		datagramSocket.receive(datagramPacket);
		
		System.out.println("client: portsource paquet recu :"+ datagramPacket.getPort());

		UdpTest.end = System.currentTimeMillis();


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


}
 
Example 19
Source File: TXIPv4PacketTest.java    From xbee-java with Mozilla Public License 2.0 4 votes vote down vote up
public TXIPv4PacketTest() throws Exception {
	destAddress = (Inet4Address) Inet4Address.getByName(IP_ADDRESS);
	destAddressBroadcast = (Inet4Address) Inet4Address.getByName(IPDevice.BROADCAST_IP);
}
 
Example 20
Source File: XBeePacketsQueueTest.java    From xbee-java with Mozilla Public License 2.0 4 votes vote down vote up
@BeforeClass
public static void setupOnce() throws Exception {
	// Create 3 64-bit addresses.
	xbee64BitAddress1 = new XBee64BitAddress(ADDRESS_64_1);
	xbee64BitAddress2 = new XBee64BitAddress(ADDRESS_64_2);
	xbee64BitAddress3 = new XBee64BitAddress(ADDRESS_64_3);
	
	// Create a couple of 16-bit addresses.
	xbee16BitAddress1 = new XBee16BitAddress(ADDRESS_16_1);
	xbee16BitAddress2 = new XBee16BitAddress(ADDRESS_16_2);
	
	// Create a couple of IP addresses.
	ipAddress1 = (Inet4Address) Inet4Address.getByName(ADDRESS_IP_1);
	ipAddress2 = (Inet4Address) Inet4Address.getByName(ADDRESS_IP_2);
	
	// Create a couple of IPv6 addresses.
	ipv6Address1 = (Inet6Address) Inet6Address.getByName(ADDRESS_IPV6_1);
	ipv6Address2 = (Inet6Address) Inet6Address.getByName(ADDRESS_IPV6_2);
	
	// Create some dummy packets.
	// ReceivePacket.
	mockedReceivePacket = Mockito.mock(ReceivePacket.class);
	Mockito.when(mockedReceivePacket.getFrameType()).thenReturn(APIFrameType.RECEIVE_PACKET);
	// RemoteATCommandResponsePacket.
	mockedRemoteATCommandPacket = Mockito.mock(RemoteATCommandResponsePacket.class);
	Mockito.when(mockedRemoteATCommandPacket.getFrameType()).thenReturn(APIFrameType.REMOTE_AT_COMMAND_RESPONSE);
	// RX64IOPacket.
	mockedRxIO64Packet = Mockito.mock(RX64IOPacket.class);
	Mockito.when(mockedRxIO64Packet.getFrameType()).thenReturn(APIFrameType.RX_IO_64);
	// RX16IOPacket.
	mockedRxIO16Packet = Mockito.mock(RX16IOPacket.class);
	Mockito.when(mockedRxIO16Packet.getFrameType()).thenReturn(APIFrameType.RX_IO_16);
	// RX64Packet.
	mockedRx64Packet = Mockito.mock(RX64Packet.class);
	Mockito.when(mockedRx64Packet.getFrameType()).thenReturn(APIFrameType.RX_64);
	// RX16Packet.
	mockedRx16Packet = Mockito.mock(RX16Packet.class);
	Mockito.when(mockedRx16Packet.getFrameType()).thenReturn(APIFrameType.RX_16);
	// ExplicitRxIndicatorPacket.
	mockedExplicitRxIndicatorPacket = Mockito.mock(ExplicitRxIndicatorPacket.class);
	Mockito.when(mockedExplicitRxIndicatorPacket.getFrameType()).thenReturn(APIFrameType.EXPLICIT_RX_INDICATOR);
	// RXIPv4Packet.
	mockedRxIPv4Packet = Mockito.mock(RXIPv4Packet.class);
	Mockito.when(mockedRxIPv4Packet.getFrameType()).thenReturn(APIFrameType.RX_IPV4);
	mockedRxIPv4Packet2 = Mockito.mock(RXIPv4Packet.class);
	Mockito.when(mockedRxIPv4Packet2.getFrameType()).thenReturn(APIFrameType.RX_IPV4);
	// RXIPv6Packet.
	mockedRxIPv6Packet = Mockito.mock(RXIPv6Packet.class);
	Mockito.when(mockedRxIPv6Packet.getFrameType()).thenReturn(APIFrameType.RX_IPV6);
	mockedRxIPv6Packet2 = Mockito.mock(RXIPv6Packet.class);
	Mockito.when(mockedRxIPv6Packet2.getFrameType()).thenReturn(APIFrameType.RX_IPV6);
}