Using which network interface each Java program uses? - java

If I have 2 public IPs on a linux system they get represented as virtual network interface names. This is what Linode says about it.
Linodes have one network interface, eth0. When you add IP addresses,
you create virtual network interfaces named eth0:1, eth0:2... eth0:n.
I need to use 2 different Java apps on the same Linode and I want each of them to use a different public IP. I would need to specify which network interface each Java instance uses. Would this be possible? I'm using Debian Linux.

You can use the ServerSocket(int port, int backlog, InetAddress address) constructor to create a server socket bound to a particular IP address (3rd parameter). The address determines the network interface that will be used.
For example:
String ip = "192.168.1.54"; // read from config file
int port = 9090; // likewise
InetAddress addr = InetAddress.getByName(ip);
ServerSocket serverSocket = new ServerSocket(port, -1, addr);
If you have two different apps and two different IP addresses you'll likely want one app to always use one IP, and the other app to always use the other one. To make sure this association doesn't change you should store the IP address each app is supposed to use in a configuration file or something similar.

Related

How can I bind two sockets to the same port on two separate programs?

I have a server.java and a client.python file. When I try the following, however, I get a "[Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions" error. Is there a way around this? Why is this happening?
client.py
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sockRecv = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind((socket.gethostname(),4000))
sockRecv.bind((socket.gethostname(),4000 + 1))
server.java
recvSocket = new DatagramSocket(4000);
sendSocket = new DatagramSocket(4000 + 1);
What your code is doing doesn't make sense, to me.
The IP address + port represents an end-point for datagram communication. If two applications were able to bind to the same end-point, which of them would receive the packets sent to the end-point? One of them? Both of them?
UDP is not a multi-cast protocol .... unless you bind to a multicast IP address.
Based on hints in your code (names of variables) I think you are trying to set up message passing between two applications on the same host. If so you should do this:
Application A binds to port P1 and sends messages to port P2
Application B binds to port P2 and sends messages to port P1.
There is no need for applications A and B bind to the same end-point; i.e. the same port ... to do what I think you are trying to do.

RMI connection with wifi and dialup internet

I have created a simple database application using rmi. It works fine with my local wireless network. But now i want to connect my client to the server through the internet. I know that, this can be achieved with setting up port forwarding in the router. But i want it to work in any computer which is connected to the internet using wifi connections, dialup
connections etc. How to do that?
what to write here? Naming.lookup ("rmi://?????????????");
As I am quite new to java, Please give me a detailed answer with a simple code example.
Thanks in advance
I hope you are messed up with Java RMI Concept. Irony is that a few days ago I was also thinking up the same except that I was thinking to connect up on my internal network.
There are two kinds of classes that can be used in Java RMI.
A Remote class is one whose instances can be used remotely. An object
of such a class can be referenced in two different ways:
1. Within the address space where the object was constructed, the object is an ordinary object which can be used like any other object.
2. Within other address spaces, the object can be referenced using an object handle. While there are limitations on how one can use an
object handle compared to an object, for the most part one can use
object handles in the same way as an ordinary object.
A Serializable class is one whose instances can be copied from one
address space to another. An instance of a Serializable class will be
called a serializable object. In other words, a serializable object is
one that can be marshaled.
SO, HERE COMES THE ANSWER TO YOUR QUESTION,ASSUMING YOU ARE TALKING ABOUT REMOTE CLASS ON DIFFERENT SYSTEM(SERVER).
The name of a remote object includes the following information:
The Internet name (or address) of the machine that is running the
Object Registry with which the remote object is being registered. If
the Object Registry is running on the same machine as the one that is
making the request, then the name of the machine can be omitted.
The port to which the Object Registry is listening. If the Object
Registry is listening to the default port, 1099, then this does not
have to be included in the name.
The local name of the remote object within the Object Registry.
The URL for a remote object is specified using the usual host, port and name:
rmi://host:port/name
host = host name of registry (defaults to current host)
port = port number of registry (defaults to the registry port number)
name = name for remote object
Assuming that your code is lying on the server having host-name as "XYZ.edu/home/CLasses"(you can give the DNS/IP-Address of server and include the location of the Class file),port-number="1099"(default) and name of the remote Object="abc" for your ABC.java Class in Server. In this way one will be able to call the Remote Object from different machines. Also, you need to keep the whole Server code on the Internet Address so that Clients can access them from the Internet(one can't access the offline-code present in your machine). Then only it can happen!!!
Here is the example Client program:
/**
* Client program for the "Hello, world!" example.
* #param argv The command line arguments which are ignored.
*/
public static void main (String[] argv) {
try {
HelloInterface hello =
(HelloInterface) Naming.lookup ("//ortles.ccs.neu.edu/Hello"); //see here the address of the server hosting the Server file,you can omit port number,it'll take default port 1099.
System.out.println (hello.say());
} catch (Exception e) {
System.out.println ("HelloClient exception: " + e);
}
}

Specify RMI endpoint address when having two interfaces

I have an rmi server on a box with two public interfaces. When a client connects, it always returns the wrong ip address in the UnicastServerRef2 [liveRef: [endpoint:[192.x.x.x:xxxx .... The connection from the client goes to the other interface with ip 10.x.x.x. Does anybody know how to solve this? I do not want to specify the ip when binding the stub. It works then, but I would like it to listen on all interfaces (0.0.0.0).
If I specify java.rmi.server.hostname=myhostname and use a RMIServerSocketFactory to create a ServerSocket[addr=myhostname/10.x.x.x,localport=xxxx], it still returns the 192.x.x.x adress to the client as remote endpoint. Weird enough I have two UnicastRemoteObjects objects on diffrerent ports and one of them returns the right address, the other not.
Any Ideas how to make it to return the endpoint with the ip of the interface the connection was made to?
That's what the java.rmi.server.hostname property is for. Set it at the exporting JVM to whatever IP address you want the clients to use to connect to it.

why ip address differs when wireless is off?

public class Main {
public static void main(String[] args) throws IOException {
InetAddress myIp = null;
try {
myIp = InetAddress.getLocalHost();
} catch (UnknownHostException ex) {
System.out.println("Exception cought.");
System.exit(0);
}
System.out.println(myIp);
}
}
I have this simple question that why my ip address is different when my wireless is off?
it's still the same computer, so why does it change? (isn't this a unique number?)
The IP address of the computer depends on the network it's connected to (and indeed, the same machine may have more than one, if it has multiple adapers).
So if I connect my machine to one of my networks, it may have the address 192.168.10.7 whereas on another of my networks, it may be 192.168.17.12. It can vary between connections as well, although in practice they tend to be a bit sticky. (It depends on how the DHCP server is configured.)
Your adapter can be configured with a fixed address, but if you do that, it has to be an address the network it's connecting to has reserved for it. Otherwise it may not work at all ("No route to host") or may conflict with another machine using the network.
.An IP address is the address of a network adapter within a specific local network.
It will be different when connected to different networks.
When not connected to any network, it will either be a link-local address or an auto-configuration address.
You might want the MAC address, which is the hardware address of a single network adapter and is not very likely to change.
The provided code returns HOSTNAME/IP-Address(xx.xx.xx.xx).
Hostname is your computer name ex: MY-PC and then you get the IP corresponding to it.
When you are connected to a network, InetAddress.getLocalHost() asks the DHCP server in the network "what is the address of MY-PC (the name of your computer)", the DHCP replies -> 33.44.55.66
Try the following CMD commands when both connected and disconnected.
\>hostname
MY-PC
\>nslookup MY-PC
44.55.66.77
When you are not connected to a network there are two possibilities:
You do not get a hostname (default is localhost)
You do get a hostname, but there is no DHCP server on the network to return an IPaddress,
so you get loopback - 127.0.0.1
If you want to "call" your computer on the network locally, use the loopback http://www.pcmag.com/encyclopedia/term/57812/loopback-address
Hope this helps
No. You're confusing IP and MAC addresses. The MAC address is a serial number of hardware(but may be programatically changed on certain chipsets).
The IP address is either software-determined or determined by the network. It can differ between networks or even with time.
IP addresses are (usually) interface specific, not machine specific.
If your machine only has one interface the difference is moot, but it matters if (for example) you have both wired and wireless ethernet.
Also note that if you do have both and attempt to use them both at the same time on the same subnet that things will likely get very confused!

IP Address not obtained in java

This code used to return my local ip address as 192.xxx.x.xxx but now it is returning 127.0.0.1 . Please help me why the same code is returning different value. Is there something that I need to watch at linux OS.
import java.util.*;
import java.lang.*;
import java.net.*;
public class GetOwnIP
{
public static void main(String args[]) {
try{
InetAddress ownIP=InetAddress.getLocalHost();
System.out.println("IP of my system is := "+ownIP.getHostAddress());
}catch (Exception e){
System.out.println("Exception caught ="+e.getMessage());
}
}
}
127.0.0.1 is the loopback adapter - it's a perfectly correct response to the (somewhat malfomed) question "what is my IP address?"
The problem is that there are multiple correct answers to that question.
EDIT: The docs for getLocalHost say:
If there is a security manager, its
checkConnect method is called with the
local host name and -1 as its
arguments to see if the operation is
allowed. If the operation is not
allowed, an InetAddress representing
the loopback address is returned.
Is it possible that the change in behaviour is due to a change in permissions?
EDIT: I believe that NetworkInterface.getNetworkInterfaces is what you need to enumerate all the possibilities. Here's an example which doesn't show virtual addresses, but works for "main" interfaces:
import java.net.*;
import java.util.*;
public class Test
{
public static void main(String[] args)
throws Exception // Just for simplicity
{
for (Enumeration<NetworkInterface> ifaces =
NetworkInterface.getNetworkInterfaces();
ifaces.hasMoreElements(); )
{
NetworkInterface iface = ifaces.nextElement();
System.out.println(iface.getName() + ":");
for (Enumeration<InetAddress> addresses =
iface.getInetAddresses();
addresses.hasMoreElements(); )
{
InetAddress address = addresses.nextElement();
System.out.println(" " + address);
}
}
}
}
(I'd forgotten just how awful the Enumeration<T> type is to work with directly!)
Here are the results on my laptop right now:
lo:
/127.0.0.1
eth0:
/169.254.148.66
eth1:
eth2:
ppp0:
/10.54.251.111
(I don't think that's giving away any hugely sensitive information :)
If you know which network interface you want to use, call NetworkInterface.getByName(...) and then look at the addresses for that interface (as shown in the code above).
When you use InetAddress.getLocalHost() you are not guaranteed to get a particular interface, ie. you could receive the loopback (127) interface or a connected one.
In order to ensure you always get an external interface, you should use the java.net.NetworkInterface class. The static getByName(String) class will give you the interface with the defined name (such as "eth0"). Then you can use the getInetAddresses() function to obtain the IP addresses (could be just one) bound to that interface.
NetworkInterface ni = NetworkInterface.getByName("eth1");
ni.getInetAddresses();
Check your /etc/host file. If you put 127.0.0.1 first, it will return this as result.
The correct way to get the ip address is to use NetworkInterface.getNetworkInterfaces() and run getInetAddresses() on each of them.
You can use the NetworkInterface.getNetworkInterfaces() method to retrieve an Enumeration of all of the network interfaces for your system.
For each of the NetworkInterface instances, you can then use the getInetAddresses() method to retrieve an Enumeration of all of the InetAddress instances associated with the network interface.
Finally, you can use the getHostAddress() method on each InetAddress instance to retrieve the IP address in textual form.
This is because you have a line in /etc/hosts like
127.0.0.1 localhost
you need to have
192.xxx.xxx.xxx localhost
Though please note that this would be very bad as to solve a code issue you should not modify linux config files. Not only is it not right (and risks breaking some other network aware apps on your linux box) it will also not work anywhere else (unless the admins of those boxes are also like minded).
javadoc for InetAddress.getLocalHost(); read "....an InetAddress representing the loopback address is returned." so it appears that the implementation of getLocalHost() is incorrect
on your UNIX and WIN boxes. The loopback address is nearly allways 127.0.0.1
Found this comment
"A host may have several IP addresses and other hosts may have to use different addresses to reach it. E.g. hosts on the intranet may have to use 192.168.0.100, but external machines may have to use 65.123.66.124. If you have a socket connection to another host you can call
Socket.getLocalAddress() to find out which local address is used for the socket."

Categories