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!
Related
IPAddress are returning different on LAN net and ZONG 4G.
I want to know the IP addresses of clients in java application so i can restrict the users for login and other roles.
But problem is that when i run below code on LAN net it returns correct IPV4 address, But if I connect Zong 4G Device it only returns 192.168.10.100 on any computer.
How to get IP Address of client?
My code:
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress();
String host = address.getHostName();
System.out.println("IP Address = " + ip);
System.out.println("host= " + host);
192.168.10.100 mean that your client is behind the NAT. There is thing called UPnP that may help you (I'm not expert and not really sure).
Alternative approach is to connect to server and ask it what it thing your IP is. It also have limitation, clients behind same NAT will have same IP.
In general building security based on IP address is bad idea.
I am trying to use the VpnService from android to setup a simple tun device on the client side and on the receiving side I have a c++ server running.
I am having a lot of problems with the VpnService. This is what I need,
I need ALL packets outbound from the Android phone to be routed to the tun device, and in the program I route it through a Datagram channel to the server. When I send a string, it works fine, but when I send other data through this Datagram channel, i don't see any UDP packets in Wireshark :\
Also, I am new to Java and Datagram channels. Here Is my code
//To establish the tunnel
builder.setSession("MyVPNService")
.addAddress("192.168.56.0", 32)
.addDnsServer("8.8.8.4")
.addRoute("0.0.0.0", 1);
mInterface=builder.establish();
What exactly are the above configurations doing? Isn't a tun device supposed to have ONE IP(from my experience from doing it on linux), then what is ""192.168.56.0", 32". Also when i try to add a route "0.0.0.0", 0 the whole android phone hangs and restarts :\
while (true) {
int length;
// Read the outgoing packet from the input stream.
length=in.read(packet_bytes);
//int length = in.read(packet.array());
if (length > 0) {
// Write the outgoing packet to the tunnel.
//packet.limit(length);
//tunnel.send(packe,server);
tunnel.send(packet,server);
packet.put(packet_bytes,0,length);
tunnel.write(packet);
packet.clear();
}
Thread.sleep(200);
// Read the incoming packet from the tunnel.
length = tunnel.read(packet);
if (length > 0) {
out.write(packet.array(), 0, length);
packet.clear();
// If we were sending, switch to receiving.
}
Thread.sleep(200);
}
This is the part where I take it from interface and put it on the other.
First, let me start by explaining Builder configuration above.
builder.setSession("MyVPNService") // This one is optional.
.addAddress("192.168.56.0", 32) // This is used to assign interface address. First param is IP address, and second in prefix length. "Prefix" length is also commonly known as subnet mask.
.addDnsServer("8.8.8.4") // This configures the DNS network for VPN network. For ex - All DNS resolutions would go to 8.8.8.4:53. Note that the DNS request packets gets routed through the tun interface.
.addRoute("0.0.0.0", 1); // This controls the IP addresses which gets routed through tun interface.
Note - that tun interface can support multiple address families (IPv4/IPv6). As an example, you can assign multiple interface addresses (say a v4, a v6, or two v6 addresses, or whatever combo).
Similarly, you can add routes that you want your VPN to handle. Now, the main question is how do you decide which routes should my VPN handle?
Well there are bunch of options.
Route everything - Adding 0.0.0.0/0 (for IPv4), and ::/0 (for IPv6) would route traffic for all destinations through VPN (Note: 0.0.0.0/0 represents entire IPv4 range i.e. 0.0.0.0 to 255.255.255.255).
Route specific routes - You would have typically noticed that talking to IoT devices does not work when VPN is running. That is typically due to "route everything" config setup which breaks local networking (ex - chromecast). So, excluding link local traffic requires doing some math that involves subtracting link local subnets from above subnets (0.0.0.0/0, ::/0 (for v6 local subnets)). The math involved is not very straightforward which makes this option a lot more complex. As for what constitutes link local subnets, here is a list from wikipedia, and from IETF for IPv4 and IPv6 special addresses.
That said, here are some answers to your questions.
I need ALL packets outbound from the Android phone to be routed to the tun device
See "route everything" above.
Isn't a tun device supposed to have ONE IP?
An interface on linux can have multiple interface addresses assigned to it from different address families.
Then what is "192.168.56.0", 32".
As explained above, first part is the IP address, and second defines the subnet mask. Also see CIDR notation.
Also when I try to add a route "0.0.0.0", 0 the whole android phone hangs and restarts.
0.0.0.0/0 means entire IPv4 address space will get routed through the VPN. Typically, a VPN cannot handle link local traffic as I have mentioned above. So, you will have to exclude certain local subnets (see links above). As for phone hanging and restarting, I'm not sure if that has anything to do with the VPN unless VPN is not handling traffic correctly (which would lead networking related apps to break).
How can I make a port forwarding from a android device to router using the IP from another device?
I want to connect from android device externally to a routers public ip:port so that I can access the hardware device that is connected to the router.(Android -> external IP:Port) -> Router -> hardware Device(hardware device has its own IP and mac).
Code:
PortMapping mapping = new PortMapping();
UnsignedIntegerTwoBytes externalPort = new UnsignedIntegerTwoBytes(22555L);
UnsignedIntegerTwoBytes internalPort = new UnsignedIntegerTwoBytes(80L);
mapping.setDescription("HardwareDescription");
mapping.setEnabled(true);
mapping.setExternalPort(externalPort);
mapping.setInternalClient("192.168.2.68");
mapping.setInternalPort(internalPort);
mapping.setProtocol(PortMapping.Protocol.TCP);
mapping.setRemoteHost("192.168.2.254");
mUpnpService = new MyUpnpServiceImpl(new PortMappingListener(mapping));
mUpnpService.getRouter();
mUpnpService.getControlPoint().search(SCAN_TIMEOUT);
UpnpServiceImpl:
private class MyUpnpServiceImpl extends UpnpServiceImpl {
public MyUpnpServiceImpl(RegistryListener... listeners) {
super(new AndroidUpnpServiceConfiguration(getWifiManager()),
listeners);
}
#Override
public Router getRouter() {
return super.getRouter();
}
#Override
protected Router createRouter(ProtocolFactory protocolFactory,
Registry registry) {
return new AndroidWifiSwitchableRouter(configuration,
protocolFactory, getWifiManager(), getConnectivityManager());
}
}
The code above doesn't crash, but also it doesn't create any port!
Is this possible?
If the answer is yes, can you point me in the right direction.
Found the answer for this question.
The first step is to enable the UPNP option on router, after this step import the library net.sbbi.upnp search for the router (IGD) device and use the method addPortMapping.
Here is an example for anyone that want to open o port on router using any IP, not just from the current device that the app runs.
https://github.com/ManolescuSebastian/Port_Forward_Android
You have to connect to your router via a desktop with any explorer (iexplorer, chrome, etc) try to connect to address 192.168.1.1 (the one that is your gateway, execute ipconfig from a cmd window and you'll see a line which says what is your gateway [the router]), type in the router's user and password and configure it. Depends on the router and model, consult the router's manual. Look for something that says NAT, Port Forward or Virtual Server. You can open a single port or a range of ports, type in the IP address where those ports should be forwarded, in this case the IP of your equipment. If any doubt, search the internet for your router's name and how to open/forward ports.
Good luck.
i have got an error in this line:
new ServerSocket(2106, 50, InetAddress.getByName("83.4.200.1"));
Error log:
Exception in thread "main" java.net.BindException: Cannot assign requested address: JVM_Bind
83.4.200.1 is my ip, when i put there 127.0.0.1 or 192.168.1.2 with same port, everything is working perfect. I have checked all ports by writing netstat -a -n, but 2106 isnt there.
Thanks a lot for reading this, i hope that u can help me with my problem
Your routers address is 83.4.200.1. It's important to note that this isn't the address that your computer responds to, but rather the internal network address 192.168.1.2. If you want to connect to your program from outside the router, you needs to set up port forwarding for 2106 on the router.
1. If you want to access this Server with IP: "83.4.200.1" through Internet, then it must
be your static ip, rather than an dynamic one.
2. Try to run this code with a private ip address or public ip address which is assigned to your pc in LAN (ie. Without internet..JUST WITH WIRELESS CONNECTION).
3. Private ip or Public ip has No meaning until and unless you are on INTERNET.. TILL THEN YOU CAN USE BOTH, AS ITS LAN.
4. Private ip ranges
Class A : 10.0.0.0 - 10.0.0.255
Class B : 172.16.0.0 - 172.31.255.255
Class C : 192.168.0.0 - 192.168.255.255
5. Public is given by your service provider, which will be anyone OUT of the private ip range. If your ip is not static, there is hardly or none of your chances to access the server over internet, there are sites that gives static ip out of your dynamic ips.
83.4.200.1 is my ip
It is the IP address of your router.
It isn't an IP address of the host you are running your code in, so you can't bind to it. You need to bind to a local address of that host, and arrange port forwarding from the router to your host. Most usually the bind-address is best omitted altogether, just specifying a port, in which case the socket will listen on all local IP addresses.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
Here's the problem, it's very simple (to understand..):
I have 2 computers at home, they both have the same public IP address (e.g. 1.2.3.4).
I have 1 computer at a coffee place (different network) so it has a different public IP address.
I want to send a message (e.g. "hi") from the computer at the coffee place to ONE of computers I have at home.
I'm using Java, think of the following very simple program for the sender (I took off exception handling for simplicity):
In main I do:
sendPacket("hi");
and I have
void sendPacket(String message){
DatagramSocket myServerSocket = new DatagramSocket(9000); // server socket
byte[] sendData = new byte[message.length()]; // build msg
sendData = message.getBytes();
InetSocketAddress destSocketAddr = new InetSocketAddress("1.2.3.4", 9000); // destination socket addr
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, destSocketAddr); // make packet
myServerSocket.send(sendPacket); // send packet
}
If I have my listener (receiver) running on both computers at home (both with the same public IP address 1.2.3.4) how can I specify which one I intend to send this message to?
If both of your home computers have the same public IP address, that means those computers are using NAT or Network Address Translation (strictly speaking, it's Port Address Translation or NAT Overload, but commonly referred to as just NAT).
What this means is that in order to initiate a connection from the outside to any of your machines inside NAT, a Port Forwarding must be set in your router (typically your modem), so that you map a specific port of your public home IP address to a specific private IP address inside your home.
Let's say you have computers A and B in your home like this:
Router / Modem
192.168.0.1
||
++=========++========++
|| ||
Computer A Computer B
192.168.0.2 192.168.0.3
Now, let's assume you need Computer A listening on TCP port 9000 (ports can mainly be TCP or UDP), you could forward public port 9000 directly to Computer A's 9000 port:
Forward TCP/UDP on public port 9000 to private port 9000 on 192.168.0.2
To send a message to computer A, just send it to 1.2.3.4:9000. But what if the other PC only listens on port 9000 too? You cannot also assign public port 9000 because it is taken by Computer A. You could do this:
Forward TCP/UDP on public port 9001 to private port 9000 on 192.168.0.3
This way, computer B still receives messages on port 9000, but they would need to be sent across the Internet to 1.2.3.4:9001. Your router's NAT automatically translates the port as the data packets enter (and leave!) your home network.
In the end, the sender would need to adjust the destination port in order to 'talk' to different machines behind NAT.
Hope this makes sense.
Typically, these NAT firewalls will port-forward traffic back to the originating computer for you.
So, if you had one machine sending traffic to your coffeeshop machine on port 5000 and the other one sending traffic to the coffeeshop machine on port 5001, the router would keep track of which port is intended for which client. Thus, when you send packets back from port 5000 it'll go to the first machine, and when you send packets back from port 5001, it'll go to the second machine.
The unfortunate part is that your machine at the coffeeshop is probably also behind a NAT firewall, and your home machines may not be able to directly address it, either.
If you can host a server on a good network, then both peers can contact the server, and relay all traffic through it. That's not a bad option but it does not scale well. (For three machines, it's no big deal. For three million machines, it matters a lot.)
You can investigate other options to try to traverse the NAT firewall such as UPnP, but those mechanisms usually require some way for clients to negotiate sessions before they'll work.