Understanding Java Network Programming with InetAddress and DatagramSocket Classes
The Java `InetAddress` class provides a high-level way to work with IP addresses and hostnames. Key methods include `getLocalHost()`, `getByName(String)`, and `getAllByName(String)`. For UDP communication, Java uses two main classes: `DatagramPacket` for encapsulating data into UDP packets and `DatagramSocket` for sending and receiving these packets. This overview covers creating sockets, sending and receiving data, and common methods for network programming, enhancing your understanding of sockets in Java.
Understanding Java Network Programming with InetAddress and DatagramSocket Classes
E N D
Presentation Transcript
Network programming With JAVA
InetAddress class • The java.net.InetAddress class is Java's high-level representation of an IP address. It is used by most of the other networking classes including both a hostname and an IP address. • Three static methods which are often used: getLocalHost(), getByName(String), getAllByName(String) Example InetAddress add1= InetAddress.getLocalHost(); InetAddress add2= InetAddress.getByName(“localhost”);
getLocalhost() try { InetAddressaddress = InetAddress.getLocalHost(); System.out.println("My name is:”+address.getHostName()); System.out.println(“My Address is:”+address.getHostAddress()); } catch (UnknownHostException e) { System.out.println(“I don't know."); }
getByName() ia = InetAddress.getByName("www.yahoo.com"); System.out.println(ia.getHostName()); System.out.println(ia.getHostAddress());
getAllByName() InetAddress[] a = ia.getAllByName("www.google.com"); for (InetAddressiac : a) { System.out.println(iac.getHostAddress()); }
Host 1 203.162.39.51 SOCKET Process A The transmitter & receiver establishes a TCP connection called socket. Socket enables data being transmitted & received on networks,. Port:4523 Process B Port:80 Host 2 10.6.8.111
Java UDP Classes • Consist of two classes: DatagramPacket and DatagramSocket. • The DatagramPacket class stuffs bytes of data into UDP packets called datagrams and lets you un-stuff datagrams that you receive. • DatagramSocket class is used for sending and receiving UDP datagrams. • To send data, you put the data in a DatagramPacket and send using a DatagramSocket. • To receive data, you receive a DatagramPacket object from a DatagramSocket and then read the contents of the packet.
DatagramPacket Constructor for sending: public DatagramPacket(byte[] data, int length, InetAddress destination, int port) public DatagramPacket(byte[] data,intoffset, int length, InetAddress destination, int port) String s = "This is a test."; byte[] data = s.getBytes(); try { InetAddressia = InetAddress.getByName("www.yahoo.com"); int port = 7; DatagramPacket dp = new DatagramPacket(data, data.length, ia, port); } …
DatagramPacket Constructor for receiving: public DatagramPacket(byte[] buffer, int length) publicDatagramPacket(byte[] buffer, int offset, int length) Example: byte[] buffer = new byte[8192]; DatagramPacketdp = new DatagramPacket(buffer, buffer.length);
The get methods • public InetAddressgetAddress() returns an InetAddress object containing the address of the remote host. • public intgetPort() returns an integer specifying the remote port. public byte[] getData() returns a byte array containing the data from the datagram. • public intgetLength() returns the number of bytes of data in the datagram.
Example String s = "This is a test."; byte[] data = s.getBytes( ); try { InetAddressia = InetAddress.getByName("www.yahoo.com"); int port = 7; DatagramPacket dp = new DatagramPacket(data, data.length, ia, port); System.out.println("This packet is addressed to " + dp.getAddress() + " on port " + dp.getPort()); System.out.println("There are " + dp.getLength() + " bytes of data in the packet"); System.out.println( new String(dp.getData(), dp.getOffset(), dp.getLength())); } catch (UnknownHostException e) { System.err.println(e);}
DatagramSocket class • To send or receive a DatagramPacket, one must open a datagram socket. • Adatagram socket is created and accessed through the DatagramSocket class.
Constructors publicDatagramSocket() throwsSocketException • This constructor is used in a client that initiates a conversation with a server. • It also receive the datagrams that a server sends back to it. • A SocketException is thrown if the socket can't be created.
Constructors Public DatagramSocket(int port) throwsSocketException • Creates a socket that listens on the particular port. • This constructor is used in a server that listens on a well-known port. • A SocketException is thrown if the socket can't be created. • There are two common reasons for the constructor to fail: • The specified port is already occupied, oryou are trying to connect to a port below 1,024.
DatagramSocketMethods 1. public void send(DatagramPacket p) throwsIOException 2. public void receive(DatagramPacket p) throwsIOException 3. public void close() 4. publicintgetLocalPort()
UDP Server Procedure • Create a UDP socket • Create a DatagramPacket to receive data • Receive data from Client. • Close UDP Socket DatagramSocket dsk= new DatagramSocket(1234); byte[] buffer= new byte[128]; DatagramPacket pk= new DatagramPacket(buffer, 128); dsk.receive(pk); System.out.println(“Client: ” + pk.getAddress() + ”:” + pk.getPort()); System.out.println(new String(buffer, 0, pk.getLength())); dsk.close();
UDP Client Procedure • Create a UDP Socket • Create a DatagramPacketto send data • Send data • Close UDP Socket DatagramSocket dsk= new DatagramSocket(); String msg= “abc”; InetAddressaddr= InetAddress.getByName(“localhost”); DatagramPacket pk= new DatagramPacket(msg.getBytes(), msg.length(), addr, 1234); dsk.send(pk); dsk.close();
ServerSocket constructor publicServerSocket (intport) throwsIOException Example: To create a server socket to listen on port 1234: try { ServerSocket server = new ServerSocket(1234); … } catch (IOExceptionie) { // error catching code … }
ServerSocketmethods • publicSocket accept() throwsIOException • publicvoid close() throwsIOException Example: To create a server socket to listen on port 1234 and accept connection request: try { ServerSocket server = new ServerSocket(1234); while (true) { Socket connection = server.accept(); provideService(connection); } } catch (IOExceptionie) { // error catching code … }
Client Socket constructor Creates a TCP socket to the specified port on the specified host and attempts to connect to the remote host. 1.publicSocket(String host, int port) throwsUnknownHostException, IOException 2.publicSocket(InetAddressaddress, intport) throwsIOException
Example try { Socket theSocket = new Socket(host, 80); System.out.println("Connected to " + theSocket.getInetAddress() + " on port " + theSocket.getPort() + " from port " + theSocket.getLocalPort() +" of “+ theSocket.getLocalAddress()); } catch (UnknownHostException ex) { System.err.println("I can't find " + host); } catch (SocketException ex) { System.err.println("Could not connect to " + host); } catch (IOException ex) { System.err.println(ex); }
Data transmission Once connected, data will be transmitted/received : 1. publicInputStreamgetInputStream() throwsIOException 2. publicOutputStreamgetOutputStream() throwsIOException
Example void doClientConnection(String computerName, intserverPort) { Socket connection; InputStreamin; OutputStreamout; try { connection = new Socket(computerName,serverPort); in = connection.getInputStream(); out = connection.getOutputStream(); } catch (IOException e) { // Error message return; } . . // Use the streams, in and out, to communicate with server. . try { connection.close(); } catch (IOException e) { } }
TCP server procedures ServerSocketwelcomeSocket = new ServerSocket(6192); Socket connectionSocket= welcomeSocket.accept(); InputStream is= connectionSocket.getInputStream(); OutputStreamos= connectionSocket.getOutputStream(); byte[] buffer= new byte[128]; intlen= is.read(buffer); System.out.println(new String(buffer,0,len)); connectionSocket.close(); welcomeSocket.close();
TCP client procedures Socket clientSocket = new Socket(host,6192); InputStream is= clientSocket.getInputStream(); OutputStreamos= connectionSocket.getOutputStream(); os.write(buffer); clientSocket.close();