java 网络协议(一)InetAddress和Socket(含源码)

1,ip地址和主机名互换
package getip;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class GetIP {

public static void main(String[] args) {
InetAddress addr= null;

if(args.length==0){
System.out.println("usage:java GetIP hostname");
System.exit(1);
}
try {
addr = InetAddress.getByName(args[0]);

} catch (UnknownHostException e) {
System.out.println("I can't find"+args[0]);
System.exit(2);
}
// byte[] add = addr.getAddress(); //返回字节数组
// for(byte i:add){
// System.out.println(i);
// }

// getHostName()返回主机名,getHostAddress()返回地址
System.out.println(addr.getHostName()+"="+addr.getHostAddress());
try {
InetAddress[] allAddrs = InetAddress.getAllByName(args[0]);//一台主机可能对应多个ip
for(InetAddress a:allAddrs){
System.out.println(a); //InetAddress.toString的隐含调用,自动输出 "主机名/ip地址"
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}


如果执行参数主机名为www.sina.com,结果如下
www.sina.com=121.194.0.206
www.sina.com/121.194.0.206
www.sina.com/121.194.0.207
www.sina.com/121.194.0.208
www.sina.com/121.194.0.209
www.sina.com/121.194.0.210
www.sina.com/121.194.0.203
www.sina.com/121.194.0.205

2,测试连接某个服务,如web服务器
package testConn;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
//测试连接web服务器
public class WebPing {
public static void main(String[] args) {

try {
InetAddress addr= null;
Socket socket = new Socket(args[0],80);//80端口是web服务
addr=socket.getInetAddress();
System.out.println("connected to "+addr);
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("can't connect to "+args[0]);
}
}

}

参数为www.sina.com结果
connected to www.sina.com/121.194.0.206
如果端口被占用出现,如参数为localhost时
can't connect to localhost

3,扫描出计算机正在使用的端口号
package usedport;

import java.io.IOException;
import java.net.ServerSocket;

//扫描出计算机中正在使用的端口,使用ServerSocket构造函数是否有异常判断
public class LocalScan {

public static void main(String[] args) {
for (int i = 0; i < 1023; i++) {
testPort(i);
}
System.out.println("completed! ");
}
private static void testPort(int i) {
try {
ServerSocket server = new ServerSocket(i);
} catch (IOException e) {
System.out.println("Port " + i + " in use!");
}
}
}


结果:

Port 135 in use!
Port 445 in use!
。。。
。。。
completed!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值