Get all the Up ip in the local network -java - java

For the Java project i need to scan the list of ip connected to the same local network via wlan or eth0 or anything. I need to get the list of ip address that are up in the local network.
I tried
InetAddress localHost = Inet4Address.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
for (InterfaceAddress address : networkInterface.getInterfaceAddresses())
{
System.out.println(address.getNetworkPrefixLength());
}
But it gives
Exception in thread "main" java.lang.NullPointerException
at com.Server.Subnet.main(Subnet.java:17)
I think i need to follow these steps.
Get the subnet address of the network that i connected
Scan all the ip address in the subnet mask
List the ip address that are up
Can you give me the right implementation way

Follow these directions
-- get your system IP
-- get your subnet mask.
-- As per your subnet mask, get the list of possible IP addresses in your subnet.&
-- Now, one by one ping them. (you can use system ping command with java)
-- check ping response, then you can decide whether the host is up or not.

I tried this program to find all the up ip in the subnet of the system connected.
package com.Server;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
public class Subnet
{
public void Subnet() throws UnknownHostException, SocketException
{
Enumeration e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration ee = n.getInetAddresses();
while (ee.hasMoreElements())
{
InetAddress i = (InetAddress) ee.nextElement();
String ip = i.getHostAddress();
String sip = ip.substring(0, ip.indexOf('.',ip.indexOf('.',ip.indexOf('.')+1) + 1) + 1);
try {
for(int it=1;it<=255;it++)
{
String ipToTest = sip+it;
boolean online = InetAddress.getByName(itToTest).isReachable(100);
if (online) {
System.out.println(ipToTest+" is online");
}
}
} catch (IOException e1) {
System.out.println(sip);
}
}
}
}
}

Related

Sending data from one computer to other connected to the same WLAN

The code is a simple program to send stuff from one computer to the other. It works if the client and server are connected to different networks, but won't work when its the same network. (port forwarding is enabled for all the ports in use)
This is for a different program which works kinda like a blockchain. I'm not sure if its a router problem. My guess is that the port forwarding won't work internally between the network clients, which would seem like a router problem. HELP!
Client Side:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception{
String ipaddress = "70.121.56.92";
DatagramSocket reciever = new DatagramSocket(3535);
DatagramPacket pacc = new DatagramPacket(new byte[98],98);
Scanner s = new Scanner(System.in);
if (s.nextLine().equals("0")) {
reciever.receive(pacc);
System.out.println(Arrays.toString(pacc.getData()));
}
}
}
Server Side:
import java.net.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception{
Scanner kb=new Scanner(System.in);
DatagramSocket me=new DatagramSocket(3537);
String msg="";
while(!msg.equals("stop")){
System.out.print("msg: ");
msg=kb.nextLine();
byte[] bs=new byte[msg.length()];
for(int i=0; i <msg.length(); ++i){
bs[i] = (byte) msg.charAt(i);
}
DatagramPacket dgp=new DatagramPacket(bs, bs.length, InetAddress.getByName("70.121.**.9*"//this is my public router address), 3535 );
me.send(dgp);
}
}
}
On a different network it shows the string i put in the client on the server console. On the same network, it gets stuck inside the reciever.recieve() method
The router routes packets received on its WAN connection to computers on the LAN, perhaps using the port-forwarding mechanism. If you send from the LAN to the WAN address, which your server is doing, then it's pretty likely that the router isn't "folding back" that address into the LAN through the port-forwarding mechanism.
You can easily validate this by having the server send to the actual LAN address of the client computer.
I don't think this is a router defect; I think that's just the way it is with NAT.

Connection time out in Java Server-Client

I have a small program where a Server-Client program is getting connected on the same network, but the same program shows a connection time out error in the client program. I have connected the two systems using LAN cable.
Server
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class DateServer {
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(9090);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} finally {
socket.close();
}
}
} finally {
listener.close();
}
}
}
Client
import java.io.BufferedReader;
import java.io.IOException ;
import java.io.InputStreamReader;
import java.net.Socket;
import javax.swing.JOptionPane;
public class DateClient {
public static void main(String[] args) throws IOException {
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
Socket s = new Socket(serverAddress, 9090);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
Since the code runs on the same computer, three possibilities come to my mind:
The problem can be either your firewall/access to port rights or having IP addresses as mentioned by other fellows.
You are setting the IP address of the server wrong.
The IP address of the server does not lie on the subnet mask of your network. If you have literaly connected the two computers with a cable (no routers in the middle) you probably haven't setup a DHCP, i.e., your ip addresses should be manually selected. If the ip is selected randomly, chances are your client computer can't find the server computer. try manually setting the ip addresses of both computers to an invalid address within the same subnet mask range and see if it works.
For example set the following addresses:
client IP: 192.168.1.10
subnetmask: 255.255.255.0
server IP: 192.168.1.11
subnetmask: 255.255.255.0
Connecting the two systems with a LAN cable is not sufficient. You have to ensure they have distinct IP addresses, are both in the same IP subnet, and/or have appropriate IP routing tables defined. More typically you would connect both via a router.

I am trying to ping www.google.com using JAVA in my office but it is not pinging the same

I am trying to ping www.google.com in my office network but it is not pinging. Code which i am using is as follows:
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class demo1 {
public static void main(String[] args) throws UnknownHostException, IOException {
try {
String address = InetAddress.getByName("www.google.com").getHostAddress();
InetAddress inet = InetAddress.getByName(address);
System.out.println("Sending Ping Request to " + address);
if(inet.isReachable(50000)){
System.out.println("Host is reachable");
}
else{
System.out.println("Host is not reachable");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I dont know what is the issue. It cant ping to www.facebook.com or www.youtube.com. I get "Host is not reachable" but it can ping to my office internal systems. In the browser all these external systems like google.com opens but Why it can't ping, I don't know. So, can anyone please help me with this?
There are many other preferred methods of pinging a server, and it appears like isReachable() has some definite design flaws. This has been addressed here: Why does InetAddress.isReachable return false, when I can ping the IP address?

How can I configure the source port for a server using Netty to send UDP packets?

I have a server task that uses Netty for socket I/O. It binds to port MY_PORT and receives UDP messages from clients. It responds to these clients, sending messages back to the clients with a destination port of MY_PORT. Using wireshark, I see that the outgoing packets from my server also have a source port of MY_PORT. This all works fine.
The people in charge of the network between the server and clients are having some issues with a load balancer. They said it would help them out if the UDP messages my server sends to the clients had a different source port than the one used for a destination.
I've looked at the Netty API, but I'm not sure how I can do this. It seems that because I've bound to a local port, I must use that for outgoing packets as well?? Here's a stripped down version of my code.
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ConnectionlessBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory;
public class UdpServer {
private final int port;
private Channel serverChannel;
public UdpServer( int port ) {
super();
this.port = port;
}
public void start() {
NioDatagramChannelFactory serverChannelFactory =
new NioDatagramChannelFactory( Executors.newCachedThreadPool(), 1 );
ConnectionlessBootstrap serverBootstrap =
new ConnectionlessBootstrap( serverChannelFactory );
serverBootstrap.setPipelineFactory( new ChannelPipelineFactory() {
#Override
public ChannelPipeline getPipeline() {
return Channels.pipeline( new SimpleChannelHandler() {
#Override
public void messageReceived( ChannelHandlerContext ctx,
MessageEvent e ) {
// TODO, handle message from client
}
} );
}
} );
serverBootstrap.setOption( "reuseAddress", Boolean.TRUE );
final InetSocketAddress trafficAddress = new InetSocketAddress( port );
serverChannel = serverBootstrap.bind( trafficAddress );
}
public void sendMessage( byte[] message, String clientIp )
throws UnknownHostException {
// TODO, how do I control the source port of this packet??
SocketAddress address =
new InetSocketAddress( InetAddress.getByName( clientIp ), port );
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer( message );
serverChannel.write( buffer, address );
}
}
You're already using bind() to set the local address. You can use connect() to connect to a specific destination port (a stretch of the "connect" concept). On a regular datagram socket you could include the remote port in the send request, but not if you're using write(). In that case you must use connect().
They said it would help them out if the UDP messages my server sends to the clients had a different source port than the one used for a destination.
This sounds like complete hooey to me. Net admins seem to have no idea about how source/destination ports are actually allocated. Even if the clients used system-allocated poets rather than a fixed port, which they probably should, the system could still allocate the same port number as the server is using.
However you could probably shut them up, or at least move them on to a different problem, by having the clients use system-allocated ports rather than a fixed port. Unless there is a client-side firewall of course ...

IP Address in a wired /wireless LAN using java

I am working on a java server-client app that transfers file btw each oda within a wired or wireless LAN, my problem now is how to detect the IP address of the client computer and the server computer in a wireless or wired LAN. Bottom-line: how to i use java code to detect the ip address of a computer in a wired or wireless LAN connection btw two computers.
Maybe jgroups can help you: http://www.jgroups.org
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
public class ListNets {
public static void main(String args[]) throws SocketException, UnknownHostException {
System.out.println(System.getProperty("os.name"));
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
if (netint.getName().equals("wlan0") || netint.getName().equals("en0")) {
displayInterfaceInformation(netint);
}
}
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("\n");
}
}

Categories