Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 1 of 1

Thread: Java networking basics

  1. #1
    Junior Member
    Join Date
    Jun 2013
    Location
    Fort Worth, Texas
    Posts
    13
    My Mood
    Fine
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Java networking basics

    Before I start i'd like to say that this is 100% MINE I am just transferring it from anarchy forums.


    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 substitute "localhost" with "www.google.com" the output will end up as "IP address is: 173.194.46.20"

    Inet6Address:



        public static void Inetsix throws UnknownHostException {
            InetAddress ipv6 = Inet6Address.getByName(ADDRESS_AS_STRING_GOES_HERE);
            System.out.println(ipv6.getHostAddress());
     
        }

    The above code would print out the IPv6 address of any given host. For example, if you replace ADDRESS_AS_STRING_GOES_HERE with a host that has an IPv6 address, it would print out said IPv6 address. However, due to the fact that I don't know of any IPv6 address using sites/hosts, I can not show you example output.


    SocketAddress:

        public static void socketaddressmethod(){
            SocketAddress address = new InetSocketAddress(HOST_AS_STRING, PORT_AS_INT);
        }

    The above code will set up a new connection to a given host on a given port. For example, if HOST_AS_STRING was replaced with "www.google.com" and PORT_AS_INT was replaced with 80, a new connection would be set up(accessible)(connections are made with a socket) with google on port 80 (Google).


    Socket:


    public static void SocketExample(){
            SocketAddress address = new InetSocketAddress(HOST_AS_STRING, PORT_AS_INT);
            Socket sock = new Socket();
            try {
                sock.connect(address);
                System.out.println("Connection made");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    The above code will make a connection to any given host/port. For example, if HOST_AS_STRING was replaced with "www.google.com" and PORT_AS_INT was replaced with 80 a new connection would be made with google on port 80 (Google) and "Connection made" would be printed to the screen.

    ServerSocket:


    public static void serversocketexample(){
            try {
                ServerSocket server = new ServerSocket();
                while(true){
                server.accept();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

    The above code will accept all incoming connections from clients to that ip address. Thus, if we use a Socket and change the IP to the IP of the server, the server will willingly accept the connection.


    DatagramPacket:

    byte[] buffer = new byte[65508];
    InetAddress address = InetAddress.getByName(ADDRESS_AS_STRING);
     
    DatagramPacket packet = new DatagramPacket(
        buffer, buffer.length, address, PORT_AS_INT);

    The above code will make a UDP packet with the size of 65508 and set it up so that when it is sent it will go straight to the given host on the given port. For example, If we changed ADDRESS_AS_STRING to "www.google.com" and PORT_AS_INT to 80, we would have made a large packet set up to send to google on port 80 (not sent until we send it with DatagramSocket).


    DatagramSocket:


    DatagramSocket datagramSocket = new DatagramSocket();
     
    byte[] buffer = MESSAGE_AS_STRING.getBytes();
    InetAddress address = InetAddress.getByName(ADDRESS_AS_STRING);
     
    DatagramPacket packet = new DatagramPacket(
            buffer, buffer.length, address, PORT_AS_INT);
    datagramSocket.send(packet);

    The above code will send a udp packet with the given message on it, to the given host on the given port. For example, if we changes MESSAGE_AS_STRING to "Hello Java Networking!" and ADDRESS_AS_STRING to "www.google.com" and PORT_AS_INT to 80, we would have sent a UDP packet with the message "Hello Java Networking!" to google on port 80 (Google)




    I HOPE THIS TUTORIAL HELPED YOU! KEEP AN EYE OUT FOR MY OTHER NETWORKING TUTORIALS FOR DIFFERENT LANGUAGES!

  2. The Following User Says Thank You to Earthly Minds For This Useful Post:

    Ram Lakshmanan (February 19th, 2019)


Similar Threads

  1. Java - The bear basics
    By Earthly Minds in forum Java Code Snippets and Tutorials
    Replies: 0
    Last Post: June 9th, 2013, 07:41 PM
  2. Java basics
    By tommyacton in forum Object Oriented Programming
    Replies: 5
    Last Post: January 5th, 2013, 06:39 AM
  3. Networking Java
    By aneel in forum JDBC and Database Tutorials
    Replies: 1
    Last Post: December 13th, 2011, 02:28 AM
  4. networking in java
    By sridhar in forum Member Introductions
    Replies: 1
    Last Post: October 4th, 2010, 11:11 AM
  5. [SOLVED] java networking
    By renu1 in forum Java Networking
    Replies: 0
    Last Post: March 12th, 2010, 11:33 AM