Polling for other Computers on a LAN in Java

Started by
12 comments, last by PhlashStudios 16 years, 11 months ago
Could anyone post some code that exemplifies this? I'm not sure how to find the broadcast address in Java.
<a href="http://eyeredux.com/campaigns/1/redirect">Hello!</a>
Advertisement
Here is a similar program I have used before (client version). The server was written in C++, but all it did was create a UDP socket (java DatagramSocket) and every time someone sent it a packet (java DatagramPacket )it just got the address of the sender and echoed "Server name = whatever" back at them.

Here is the client source (includes a stupid GUI, written hastily, don't blame me [smile] )

import java.io.IOException;import java.net.InetAddress;import java.net.*;import java.net.UnknownHostException;import javax.swing.*;import java.awt.*;import java.awt.event.*;public class ServerQuery{	private static final int QUERY_PORT = 1234;//13457;	InetAddress address = null;	DatagramSocket socket = null;	//DatagramPacket packet;	JTextArea messageArea;		ServerQuery()	{                //DatagramPacket packet;		JFrame frame = new JFrame("ServerQuery");		messageArea = new JTextArea("Servers:\n");		messageArea.setSize(300,300);		messageArea.setEditable( false );		frame.setSize(300,300);		Container pane = frame.getContentPane();		pane.setLayout( new BorderLayout() );		pane.add( new JScrollPane(messageArea), BorderLayout.CENTER );				JButton button = new JButton("refresh");		button.addActionListener( 			new ActionListener()				{ 					public void actionPerformed( ActionEvent e )					{ 						refresh();					}				}			);		pane.add( button, BorderLayout.SOUTH );		frame.setVisible( true );		frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);				try		{			//address = InetAddress.getByAddress(ip);			socket = new DatagramSocket();			socket.setBroadcast( true );			refresh();		}		catch( SecurityException e )		{			print( e.toString() );		}		catch( IOException e )		{			print( e.toString() );		}	}		public static void main( String[] args )	{		ServerQuery query = new ServerQuery();		query.run();	}		public void print( String msg )	{		messageArea.setText( messageArea.getText() + '\n' + msg );	}		private void refresh()	{		messageArea.setText("Servers:\n");		try		{			byte []ip = new byte[4];			for( int i = 0 ; i < 4; ++i )			{				ip = (byte)255;			}                        address = InetAddress.getByAddress(ip);			String meaningless = "hi server how are you??? im grand thanks just tell us your ip, no?";			meaningless += '\0';			DatagramPacket packet = new DatagramPacket( meaningless.getBytes(), meaningless.length() );			packet.setPort( QUERY_PORT );			packet.setAddress( address );			socket.send( packet );		}		catch( UnknownHostException e )		{			print( e.toString() );		}		catch( SecurityException e )		{			print( e.toString() );		}		catch( IOException e )		{			print( e.toString() );		}	}		public void run()	{		while(true)		{			try			{				byte [] bytes = new byte[1024];                                DatagramPacket packet = new DatagramPacket(bytes,bytes.length);				socket.receive( packet );								int indexOfNul = 0;				while( bytes[indexOfNul] != 0 )				{					indexOfNul++;				}				print( new String( packet.getData(),0,indexOfNul ) );				print( "Server at address : " + packet.getAddress().toString() );			}			catch( IOException e )			{				print( e.toString() );			}		}	}}


Here is a simple echo server I wrote for some reason ( I think it was to test UDP through a firewall or some stupid reason ). Note the port is different.

import java.net.*;class Echo{	private static final int SIZE = 1024;	public static void main( String [] args )	{		System.out.println("UDP echo server running...");		try		{			byte [] data = new byte[SIZE];			DatagramPacket packet = new DatagramPacket(data,SIZE);			DatagramSocket socket = new DatagramSocket(1234);//24567);			while(true)			{				try				{					socket.receive( packet );					String string = new String( packet.getData(),0 , packet.getLength()  );					System.out.println( java.util.Calendar.getInstance().getTime().toString() + ": Echoing message from " + packet.getAddress().toString() + ':' + packet.getPort() + " " + string );					packet.setAddress( packet.getAddress() );					socket.send( packet );				}				catch( Exception e )				{					System.out.println(e);				}			}		}		catch( Exception e )		{			System.out.println(e);		}	}}


You can try that (it may need a tiny but of work, this was old, throw away code).

As for your question as to how to get the broadcast address, this is the way I seem to have chosen:
byte []ip = new byte[4];for( int i = 0 ; i < 4; ++i ){	ip = (byte)255;}address = InetAddress.getByAddress(ip);


Im sure there are easier ways, like this probably:
address = InetAddress.getByName("255.255.255.255");
You can mask the address like so:
InetAddress address = InetAddress.getByName("192.168.0.1");byte[] addrBytes= address.getAddress();addrBytes[3]=(byte)255;InetAddress newAddress = InetAddress.getByAddress(addrBytes);

Thanks guys.
<a href="http://eyeredux.com/campaigns/1/redirect">Hello!</a>

This topic is closed to new replies.

Advertisement