Easy Tutorial
❮ Net Url Date Time Datetime ❯

Java Example - Connecting to a Specified Host using Socket

Java Examples

The following example demonstrates how to use the getInetAddress() method of the net.Socket class to connect to a specified host:

Main.java File

import java.net.InetAddress;
import java.net.Socket;

public class WebPing {
    public static void main(String[] args) {
        try {
            InetAddress addr;
            Socket sock = new Socket("www.tutorialpro.org", 80);
            addr = sock.getInetAddress();
            System.out.println("Connected to " + addr);
            sock.close();
        } catch (java.io.IOException e) {
            System.out.println("Could not connect to " + args[0]);
            System.out.println(e);
        }
    }
}

The above code outputs the following result when run:

Connected to http://www.tutorialpro.org/222.73.134.120

Java Examples

❮ Net Url Date Time Datetime ❯