How can I bind serversocket to specific IP? - java

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);

Related

java udp send from specific IP address

I have a server with many IP addresses, and a UDP socket bound to 0.0.0.0 so I can receive UDP from any of them. How can I specify the source IP address to use in the UDP packets I am sending? My current implementation is using NIO so maybe using the DatagramChannel to perform the sending is the problem.
I gave up on a clean solution and just use a bound DatagramSocket per IP address on server that can be used to send UDP with the specific source IP for the outbound packets.
The following program demonstrates that your requirement is imaginary. It shows that a datagram packet originated at a DatagramSocket bound to 0.0.0.0 is delivered with a source-address of 127.0.0.1.
public static void main(String[] args) throws IOException
{
DatagramSocket ds1 = new DatagramSocket(0);
int port = ds1.getLocalPort();
System.out.println(ds1.getLocalAddress());
DatagramSocket ds2 = new DatagramSocket();
byte[] bytes = {0x01};
SocketAddress sa = new InetSocketAddress("localhost", port);
DatagramPacket dp = new DatagramPacket(bytes, 0, bytes.length, sa);
ds2.send(dp);
ds1.receive(dp);
ds2.send(dp);
ds2.receive(dp);
System.out.println(dp.getAddress());
}

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 to listen on IP and Port in Java ? with ServerSocket?

I'm creating a client/server chat (Multi-threading) app in Java .
I want to listen to clients on a specific port and IP .
When I do this :
ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept(); // accept connection
// more code
Does it mean that the IP that I'm listening is 127.0.0.1 ? i.e. localhost ?
From a look on the constructor of ServerSocket object , we have 3 types of constructors :
public ServerSocket(int port) throws IOException
public ServerSocket(int port, int backlog) throws IOException
public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException
What constructor should I use , if I want to get clients from OTHER IP addresses
This one :
public ServerSocket(int port) throws IOException
Or this one :
public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException
?
Much appreciated
Does it mean that the IP that I'm listening is 127.0.0.1 ? i.e. localhost ?
No. It means you are listening on all IP addresses of your host.
What constructor should I use if I want to get clients from other IP addresses?
This one.
InetAddress inetAddress = InetAddress.getByName("192.168.1.1");
int port =8081;
serverSocket = new ServerSocket(port,5,inetAddress);
Do you mean this?May it will helpful.
And the second arguement means - requested maximum length of the queue of incoming connections(from jdc).

How to get the IP address for remote host using 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

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