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.
Related
I have a C# WPF application that uses TCPListener to start a Server in my computer, and an android app that works as a client. It works perfectly when I start the server and emulate the app in my computer, but most of the time it just doesn't work when I use my smartphone to connect to my computer, it only works some times after I restarted my router DHCP and my smartphone.
If you need, here's the connection code
Server:
private static IPAddress ipAd;
private static TcpListener server;
private static TcpClient client;
public static void start() {
//Already tried with both
ipAd = IPAddress.Parse(TCPServer.GetLocalIPAddress());
//ipAd = IPAddress.Parse("127.0.0.1");
server = new TcpListener(ipAd, 1209);
client = default(TcpClient);
try {
server.Start();
Console.WriteLine("Server started");
} catch {
Console.WriteLine("Failed to start server");
}
Client:
Socket socket = null;
String response = new String();
try{
//connect This ipAddress is the same in my desktop
InetAddress ipAd = InetAddress.getByName(ipAddress);
socket = new Socket(ipAd, 1209);
//send
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.write(message.getBytes());
}
...
Thanks for your time, I've should had dedicated more to my Computer Networks class...
Should I redirect some specific port? Have some specific configurations in my router/firewall? I think I'm missing something
This would work when your devices located in the same network in terms of IP routing. However even part of the most simple SOHO grade WiFi routers/AP enable so called device isolation, denying access from wifi devices in the network access between them or to clients, connected with ethernet.
To make this setup work reliably you need to ensure the following:
Use external address of your router in the mobile application. (You can discover it browsing http://whatismyip.org from the server)
Setup port forwarding in your router for particular port to particular IP in your internal network.
As for privided source code, you'd rather use 0.0.0.0 as bind address in the server app, because default .NET implementation will select first available IP address and it may be not the one you're using for connection in the mobile app or not related to the same network. This approach may have security and convenience (coexistence) problems in case of complex networking setup, but will work good for most of the cases.
I'm trying to write a program that will show a DHCP client list in Java. I want to get the IP addresses, MAC addresses and the host names of all the devices connected to my wifi network.
I have a Belkin router. Its homepage has a 'DHCP client list' option which when clicked shows me this table :
That's exactly what I'm looking for. But I want to show all this data in the form of a list in a Java Swing program. I also want to be able to update this list by pressing a refresh button. Is there any way to achieve this?
It should look something like this :
I've written a basic java program that shows all the IP addresses that are online. Here's the code :
public static void main(String[] args) throws IOException {
InetAddress localhost = InetAddress.getLocalHost();
// this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
for (int i = 1; i <= 254; i++)
{
ip[3] = (byte)i;
InetAddress address = InetAddress.getByAddress(ip);
if (address.isReachable(1000))
{
// machine is turned on and can be pinged
System.out.println(address + "is online");
}
else if (!address.getHostAddress().equals(address.getHostName()))
{
// machine is known in a DNS lookup
System.out.println(address + "is in a DNS lookup");
}
else
{
// the host address and host name are equal, meaning the host name could not be resolved
System.out.println(address + " is not online");
}
}
}
But this doesn't serve the purpose and it's really slow. I want to write a Swing program that'll show me the DHCP client list as seen in the image above.
Any help is appreciated.
I would think about three possible alternatives:
1-The one you implemented that is slow but it can work. You need to find a JAVA API to get the MAC addresses of received messages (I don't know if it exists or not). You can also send ARP messages asking "who has this IP address) and obtain the MAC address from the response. Use some Java interface for pcap library: jNetPcap vs Jpcap , http://jnetpcap.com/
2-Create an app that accesses your router web interface using HTTP and sending the appropriate messages with data as if you were using the UI. In this way you can programatically follow the steps a human would go and get the list that you browser shows, parse it and obtain the data.
3-If the router/access point provides a web API, which I doubt, you can use it.
I'm developing an android app which is used to remote control PC from an android phone. I managed to develop a fully functional app (client and server(java) app) except i have to specify for the client on which IP to connect. Both client and server are opening a socket and listening on port 8998. Is there a way of getting a list of servers (on client side) listening on that specific port?
Thank you in advance,
Kristian
try {
InetAddress serverAddress = InetAddress.getByName(Constants.SERVER_IP); // getting the inet adress of the server
NetworkInterface netInterface = NetworkInterface.getByInetAddress(serverAddress); // getting the interface name where all other servers should be
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
for (InetAddress inetAddress : Collections.list(addresses)) {
out.println("InetAddress: " + inetAddress);
Log.d("adresses", String.valueOf(inetAddress));
}
}catch(IOException e){
Log.e("err", "Unknown hostname!");
}
Is there a way of getting a list of servers (on client side) listening on that specific port?
Iterate over all relevant IP addresses and see if you can connect on that port for each of them. It is up to you to decide your algorithm for "all relevant IP addresses", though a common one is to check all on the /24 subnet (e.g., if the device's IP address is 192.168.1.57, check all 192.168.1.* addresses except 57).
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).
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!