Introduction
In this article, we discuss the InetAddress, DatagramSocket and DatagramPacket classes in Java.
InetAdress class
The java.net.InetAddress class represents an IP address. The Inet Address class provides methods to get the IP of any hostname.
Some commonly used public methods are:
static InetAddress getByName (String host) throws UnknownHostException
used to return the IP of the given host.
used to return the IP of the given host.
static InetAddress getLocalHost() throws UnknownHostException
used to return the LocalHost IP and name.
used to return the LocalHost IP and name.
String getHostName()
used to return the hostname of the IP address.
used to return the hostname of the IP address.
String getHostAddress()
used to return the IP address in string format.
used to return the IP address in string format.
Example
- import java.net.*;
- import java.io.*;
- public class InetEx {
- public static void main(String[] args) {
- try {
- InetAddress ipadd = InetAddress.getByName("www.c-sharpcorner.com");
- System.out.println("Host Name Of Given Host: " + ipadd.getHostName());
- System.out.println("IP Address Of Given Host: " + ipadd.getHostAddress());
- } catch (Exception ey) {
- System.out.println(ey);
- }
- }
- }
Output

DatagramSocket class (Networking)
This class shows a connection-less socket for receiving and sending datagram packets. Datagrams are basically information so there is no guarantee of its content, arrival or arrival time. The DatagramPacket classes and DatagramSocket are used for connection-less socket programming.
Some commonly used constructors are:
DatagramSocket(int portno) throws SocketEeption
creates a datagram socket and bind it with the given Port number.
creates a datagram socket and bind it with the given Port number.
DatagramSocket() throws SocketEeption
creates a datagram socket and bind it with the available Port Number on the localhost machine.
creates a datagram socket and bind it with the available Port Number on the localhost machine.

Join the conversation! Your thoughts help the community grow.