Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Java, Web
Expertise: Intermediate
Oct 19, 1998



Application Security Testing: An Integral Part of DevOps

Network Programming, UDP Echo Client

When network testing, it is useful to have a client program connects to a UDP server and gets an echo of a text string that you send to the server:
import java.net.*;
import java.io.*;
import java.util.*;

class SocketUdpEcho01{
	public static void main(String[] args){
		String server = "www.austin.cc.tx.us";
		int port = 7; //echo port
		String msg = "This is a UDP echo test";

			//Convert the message to a byte array
			byte[] udpMsg = msg.getBytes();
			InetAddress addr = InetAddress.getByName(server);
			//Create a packet
			DatagramPacket packet = 
				new DatagramPacket(udpMsg,udpMsg.length,addr,port);
			//Get a datagram socket to send the message
			DatagramSocket datagramSocket = new DatagramSocket();
			//Send the message
			//Overwrite the msg in the packet to confirm that
			//an echo is really received
			byte[] dataArray = packet.getData();
			for(int cnt = 0; cnt < packet.getLength(); cnt++)
				dataArray[cnt] = 'x';
			//Display overwritten version
			System.out.println(new String(packet.getData()));
			//Receive the echo into the same packet.
			//Display the echo
			System.out.println(new String(packet.getData()));
		}//end try
		catch(UnknownHostException e){
					"Connection Failure. Are you online?");
		}//end catch UnknownHostException
		catch(SocketException e){System.out.println(e);}
		catch(IOException e){System.out.println(e);}
	}//end main
}//end class SocketUdpEcho01
After editing your favorite Web server name into the string named server, the program should display:
If another message is displayed, you should try another server. This code was tested using JDK 1.1.6 under Win95.
Richard G.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date