例:InetAddress ia = InetAddress.getByName("www.sun.com");
import java.net.*; /** *演示InetAddress类的基本使用 */ public class InetAddressDemo{ public static void main(String[] args){ try{ //使用域名创建对象 InetAddress inetAd=InetAddress.getByName("www.163.com");//getByName是InetAddress类的静态方法 System.out.println(inetAd); //使用IP创建对象 InetAddress inetAd2=InetAddress.getByName("127.0.0.1"); System.out.println(inetAd2); //获得本机地址对象 InetAddress inetAd3=InetAddress.getLocalHost(); System.out.println(inetAd3); //获得对象中储存的域名 String host=inetAd3.getHostName(); System.out.println("域名: "+host); //获得对象中储存的IP String ip=inetAd3.getHostAddress(); System.out.println("IP: "+ip); } catch(Exception e){ } } }
send(DatagramPacket p) 发送数据报。
如下面的程序:DatagramDemo.java
import java.io.*; import java.net.*; class DatagramDemo{ public static void main(String[] args){ String host="localhost"; if(args.length==1){ System.out.println("args.length=="+args.length); host=args[0]; } DatagramSocket s=null; try{ s=new DatagramSocket(); byte[] buffer; buffer=new String("Send me a datagram").getBytes(); InetAddress inetAddr=InetAddress.getByName(host); DatagramPacket dataGramPacket=new DatagramPacket(buffer,buffer.length,inetAddr,10000);//你将这里改为1000端口,再看运行的MCseverClient会不会收到报文 s.send(dataGramPacket); byte[] buffer2=new byte[100]; dataGramPacket=new DatagramPacket(buffer2,buffer2.length,inetAddr,1000); s.receive(dataGramPacket); System.out.println(new String(dataGramPacket.getData())); } catch(IOException e){ System.out.println(e.toString()); } finally{ if(s!=null) s.close(); } } }注意:上面程序的运行结果是在下面的程序(MCseverClient.java)运行界面中看到,也即要建立起服务器客户端
import java.io.*; import java.net.*; class MCseverClient{ public static void main(String[] args)throws IOException{ MulticastSocket s=new MulticastSocket(10000);//MulticastSocket ???服务器端开放多个端口? InetAddress group=InetAddress.getByName("231.0.0.1"); s.joinGroup(group); for(int i=0;i<10;i++){ byte[] buffer=new byte[256]; DatagramPacket datagramPacket=new DatagramPacket(buffer,buffer.length); s.receive(datagramPacket); byte[] buffer2=new byte[datagramPacket.getLength()]; System.arraycopy(datagramPacket.getData(),0,buffer2,0,datagramPacket.getLength()); System.out.println(new String(buffer2)); /*if(datagramPacket.getData()!=null){ byte[] sendStr; sendStr=new String("I received from "+datagramPacket.getAddress()).getBytes(); DatagramPacket datagramSend=new DatagramPacket(sendStr,sendStr.length,datagramPacket.getAddress(),1000); DatagramSocket sendSock=new DatagramSocket(); sendSock.send(datagramSend); }*/ } s.leaveGroup(group); s.close(); } }