How to get the IP address for remote host using Java - java

I need to get the IP address for remote hosts. I tried the following and works fine:
socket = factory.createSocket(hostName, port);
InetAddress remoteIP = socket.getInetAddress();
String[] remoteIPOnly = remoteIP.toString().split("\\/");
System.out.println("Remote IP is: "+remoteIPOnly[1]);
But, I need a way where I don't have to specify a port number. I.e, I need the IP for a remote host despite the port number. Is this possible ? Is it possible to get the IP without creating socket from the first place ?

Try this:
InetAddress inetAddress = InetAddress.getByName("www.google.com");
byte[] raw = inetAddress.getAddress();
The byte array now contains the IP addresses bytes.

Use getHostAddress() as below:
InetAddress inetAddress = InetAddress.getByName("www.google.com");
String ipAddress = inetAddress.getHostAddress();
System.out.println(ipAddress );//prints 66.152.109.61

Related

Get address/port of ServerSocket that a Socket is trying to connect to? (Java)

I can't word this well, so let me give you an example.
If my code is:
Socket socket = new Socket("1.2.3.4", 80);
and then I run two methods like:
System.out.println(socket.getAddressOfHost());
System.out.println(socket.getPortOfHost());
I want it to return:
1.2.3.4
80
Is this possible and what are the names of these methods?
After the Socket is connected to the server, those values can be retrieved using the Socket.getInetAddress() and Socket.getRemoteSocketAddress() methods:
InetAddress addr = socket.getInetAddress();
// InetAddress does not expose port numbers...
System.out.println(addr.getHostAddress());
System.out.println(addr.getHostName());
InetSocketAddress sockaddr = (InetSocketAddress) socket.getRemoteSocketAddress();
InetAddress addr = sockaddr.getAddress();
System.out.println(addr.getHostAddress());
System.out.println(addr.getHostName());
System.out.println(sockaddr.getPort());
Refer to the Socket documentation for more details.

How can I bind serversocket to specific IP?

If I have a String representing an IP address (IPv4 or IPv6) how can I create a ServerSocket and bind to this IP without caring if the IP passed in, is IPv4 or IPv6?
I see that there is a constructor:ServerSocket(int port, int backlog, InetAddress bindAddr) but InetAddress does not seem to offer any constructors and its subclasses have names specific to IPv4 and IPv6.
So how can I bind the socket to the IP?
You can use the factory method INetAddress.getByName. It'll figure out which subclass to use. For example:
InetAddress addr = InetAddress.getByName("127.0.0.1");
// or
InetAddress addr = InetAddress.getByName("::1");
// and now you can pass it to your socket-constructor
ServerSocket sock = new ServerSocket(1234, 50, addr);

UDP broadcast on Java doesn't work

I'm trying to send a UDP broadcast on IP address "255.255.255.255" for device discovery in my network. The program executes, but I don't see anything in Wireshark. when I'm changing the IP address to a known IP in my network, I can see the packets in Wireshark. what's going on ?
This is my code:
public static void main(String args[]) throws Exception
{
String Broadcastaddress = new String("255.255.255.255");
int port = 9876;
DatagramSocket serverSocket = new DatagramSocket();
serverSocket.setBroadcast(true);
InetAddress IPAddress = InetAddress.getByName(Broadcastaddress);
System.out.println("Sending Discovery message to " + IPAddress + "Via UDP port " + port);
byte[] sendData = new byte[4];
sendData[0] = 'F';
sendData[1] = 'I';
sendData[2] = 'N';
sendData[3] = 'D';
DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,IPAddress,port);
while (true)
{
serverSocket.send(sendPacket);
System.out.println("Packet sent");
}
}
OK, I found an answer. Windows 7 doesn't support 255.255.255.255 broadcasts anymore, apparently it was an opening to various threats. To broadcast, one needs to use a different approach.
This is a small explenation from Wikipedia:
The broadcast address for an IPv4 host can be obtained by performing a bitwise logical OR operation between the bit complement of the subnet mask and the host's IP address.
Example: to broadcast a packet to an entire IPv4 subnet using the private IP address space 100.16.0.0/12, which has the subnet mask 255.240.0.0, the broadcast address is: 100.16.0.0 | 0.15.255.255 = 100.31.255.255.
A special definition exists for the IP broadcast address 255.255.255.255. It is the broadcast address of the zero network or 0.0.0.0, which in Internet Protocol standards stands for this network, i.e. the local network. Transmission to this address is limited by definition, in that it is never forwarded by the routers connecting the local network to the Internet.

Converting string to IP Address in java(android)

When i convert string ("192.168.0.105") to InetAddress in java (android). I am getting "/192.168.0.105". An extra "/" is coming in InetAddress, which causes the socket not to be created.
How do i get rid of "/".
Regards,
Syed Mustehsan Ikram
You can use getHostAddress() method of InetAddress to get host address without /.
And if you are using InetSocketAddress then use getAddress().getHostAddress() to get host ip without /.
InetAddress inetAddress = InetAddress.getByName("192.168.0.105");
System.out.println(inetAddress.getHostAddress());
InetSocketAddress address = new InetSocketAddress("192.168.0.105", 5555);
System.out.println(address.getAddress().getHostAddress());
myString = myString.replace("/", "");

Creating InetAddress object in Java

I am trying to convert an address specified by an IP number or a name, both in String (i.e. localhost or 127.0.0.1), into an InetAdress object. There's no constructor but rather static methods that return an InetAddress. So if I get a host name it's not a problem, but what if I get the IP number? There's one method that gets byte[] but I'm not sure how that can help me. All other methods gets the host name.
InetAddress API documentation
You should be able to use getByName or getByAddress.
The host name can either be a machine
name, such as "java.sun.com", or a
textual representation of its IP
address
InetAddress addr = InetAddress.getByName("127.0.0.1");
The method that takes a byte array can be used like this:
byte[] ipAddr = new byte[]{127, 0, 0, 1};
InetAddress addr = InetAddress.getByAddress(ipAddr);
From the API for InetAddress
The host name can either be a machine
name, such as "java.sun.com", or a
textual representation of its IP
address. If a literal IP address is
supplied, only the validity of the
address format is checked.
ip = InetAddress.getByAddress(new byte[] {
(byte)192, (byte)168, (byte)0, (byte)102}
);
InetAddress.getByName also works for ip address.
From the JavaDoc
The host name can either be a machine
name, such as "java.sun.com", or a
textual representation of its IP
address. If a literal IP address is
supplied, only the validity of the
address format is checked.
The api is fairly easy to use.
// Lookup the dns, if the ip exists.
if (!ip.isEmpty()) {
InetAddress inetAddress = InetAddress.getByName(ip);
dns = inetAddress.getCanonicalHostName();
}
InetAddress class can be used to store IP addresses in IPv4 as well as IPv6 formats. You can store the IP address to the object using either InetAddress.getByName() or InetAddress.getByAddress() methods.
In the following code snippet, I am using InetAddress.getByName() method to store IPv4 and IPv6 addresses.
InetAddress IPv4 = InetAddress.getByName("127.0.0.1");
InetAddress IPv6 = InetAddress.getByName("2001:db8:3333:4444:5555:6666:1.2.3.4");
You can also use InetAddress.getByAddress() to create object by providing the byte array.
InetAddress addr = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
Furthermore, you can use InetAddress.getLoopbackAddress() to get the local address and InetAddress.getLocalHost() to get the address registered with the machine name.
InetAddress loopback = InetAddress.getLoopbackAddress(); // output: localhost/127.0.0.1
InetAddress local = InetAddress.getLocalHost(); // output: <machine-name>/<ip address on network>
Note- make sure to surround your code by try/catch because InetAddress methods return java.net.UnknownHostException
This is a project for getting IP address of any website , it's usefull and so easy to make.
import java.net.InetAddress;
import java.net.UnkownHostExceptiin;
public class Main{
public static void main(String[]args){
try{
InetAddress addr = InetAddresd.getByName("www.yahoo.com");
System.out.println(addr.getHostAddress());
}catch(UnknownHostException e){
e.printStrackTrace();
}
}
}

Categories

Resources