JAVA NETWORKING TUTORIAL
Imports Needed:
Java.io.*
Java.util.*
Java.net.*
Objects Used:
InetAddress - creates an IP connection to a specified host
Inet4Address - Creates an IPv4 connection to a specified host
Inet6Address - Creates an IPv6 connection to a specified host
SocketAddress - provides an immutable object used by sockets for binding, connecting, or as returned values. (Abstract class (used with InetAddress))
Socket - Opens a TCP socket to a specific IP address
ServerSocket - Creates a server for Sockets to connect to (Only needed for client/server networing)
DatagramPacket - Creates a UDP packet which connects through the DatagramSocket
DatagramSocket - creates a UDP socket to send DatagramPackets
Examples/explenations of all:
InetAddress:
public static void inetmethod() throws UnknownHostException{
InetAddress address =InetAddress.getByName(ADDRESS_AS_STRING_GOES_HERE);
System.out.println(address.getHostAddress() +" || "+ address.getHostName()); }
The above doe will print out the IP address of anything given and it's host name. For example, if ADDRESS_AS_STRING_GOES_HERE was substituted with "www.google.com" then "173.194.46.20 || http://www.google.com" would print out.
Inet4Address:
import java.net.*; import java.util.*;
public class GetAddress {
public static void main(String[] args) throws Exception { String result = ""; InetAddress i = Inet4Address.getByName("localhost"); //returns the raw IP address of object. byte b[] = i.getAddress(); System.out.print("IP address is: "); for (int j = 0; j < b.length; j++) { result+= b[j]; result+= "."; } System.out.print(result); }
}
The above code will print out the IPv4 address of any given host. For example, the above code, will print out "IP address is: 127.0.0.1". However, if we