Java Examples - Connect to a specified host using Socket

Java 实例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.example.com", 80); addr = sock.getInetAddress(); System.out.println("Connected to" + addr); sock.close(); } catch (java.io.IOException e) { System.out.println("Unable to connect" + args[0]); System.out.println(e); } } }

The output of running the above code is:

连接到 http:/www.example.com/222.73.134.120

Java 实例Java Examples

Other Extensions