Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between SocketAddress and InetAddress in Java [duplicate]

Tags:

java

It's unclear what SocketAddres is designed for. As far as I see there is just one reasonable way to use it: through InetSocketAddress. It's confusing.

like image 271
Antonio Avatar asked Nov 03 '25 11:11

Antonio


2 Answers

InetAddress will give the IP address of specified web site example :

InetAddress ip=InetAddress.getByName("www.google.com");  

System.out.println("Host Name: "+ip.getHostName());  
System.out.println("IP Address: "+ip.getHostAddress());  

SocketAdress is used to create the Socket at end point with InetAddress and port number

 InetAddress addr = InetAddress.getByName("www.google.com");
    int port = 80;
    SocketAddress sockaddr = new InetSocketAddress(addr, port);

    Socket sock = new Socket();

    sock.connect(sockaddr);
like image 88
Lova Chittumuri Avatar answered Nov 06 '25 00:11

Lova Chittumuri


From the Documentation of SocketAddress:

This class represents a Socket Address with no protocol attachment. As an abstract class, it is meant to be subclassed with a specific, protocol dependent, implementation.

From the Documentation of InetAddress:

This class represents an Internet Protocol (IP) address.

So one represents a socket without any protocol as abstract class, the other represents an IP-address. What you are most probably looking for is an InetSocketAddress (a socket, bound to a specific IP/Hostname and port).

like image 29
Turing85 Avatar answered Nov 06 '25 01:11

Turing85