简体   繁体   中英

java.net.UnknownHostException Cannot create socket. Java

I read some manuals and tried to create Socket, how it looks like in examples.

Socket socket = new Socket(InetAddress.getByName("http://google.com"), 80);

or

Socket socket = new Socket("http://google.com", 80);

In any case, I get the UnknownHostException:

java.net.UnknownHostException: http://google.com: Name or service not known

How will it work?

import java.io.*;
import java.net.*;

public class socket_client
{
    public static void main(String[] args) throws IOException 
    {
        Socket s = new Socket();
    String host = "www.google.com";

        try
        {
        s.connect(new InetSocketAddress(host , 80));
        }

        //Host not found
        catch (UnknownHostException e) 
        {
            System.err.println("Don't know about host : " + host);
            System.exit(1);
        }

        System.out.println("Connected");
    }
}

try www.google.com instead. I just tried telnet http://google.com and it doesn't connect. telnet www.google.com 80 does connect however.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM