package com.xudeyu.socket;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class SocketTest
{
public static void main(String[] args) throwsIOException
{
SocketConnTest s = new SocketConnTest();
// s.socketConn("www.baidu.com", 80);
s.getInetAddress(null);
}
}
class SocketConnTest
{
public void getInetAddress(String host) throwsUnknownHostException
{
if (host != null)
{
// 获取主机的所有的可用IP地址
InetAddress[] ips = InetAddress.getAllByName(host);
// 循环打印出地址
for (InetAddress ip : ips)
{
System.out.println(ip);
}
}
else
{
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost);
}
}
@SuppressWarnings("resource")
public void socketConn(String ip, int port) throwsIOException
{
// creeate a socket ,if failed .throwsUnKnowHostException;
// Socket socket = new Socket(ip, port);
// socket.setSoTimeout(1000);
Socket socketTime = new Socket();
socketTime.connect(newInetSocketAddress(InetAddress.getByName(ip),
port), 100);
try
{
// get stream form host and print it;
InputStream inStream = socketTime.getInputStream();
Scanner scan = new Scanner(inStream);
while (scan.hasNextLine())
{
String line = scan.nextLine();
System.out.println("message " + line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
socketTime.close();
}
}
}