Inetaddress

InetAddress address = InetAddress.getByName("主机名");
String ip = address.getHostAddress(); System.out.println(ip);//IP地址


UDP

发送端

public class clientdemo {
    public static void main(String[] args) throws IOException {
        //找码头
        DatagramSocket ds = new DatagramSocket();  
        //打包礼物
        String s = "给老丈人的礼物";
        byte[] bytes = s.getBytes();
        //发送
        InetAddress ad = InetAddress.getByName("127.0.0.1"); //地址改为广播地址就为广播
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length,ad,10000);
        ds.send(dp);
        //付钱,(释放)
        ds.close();
    }
}

接收端

public class serverdemo {
    public static void main(String[] args) throws IOException {
        //找码头
        DatagramSocket ds = new DatagramSocket(10000);
        //创建新箱子
        byte[] bytes = new byte[1024];
        //接收礼物
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
        //获取礼物
        ds.receive(dp);
        int length = dp.getLength();
        System.out.println(new String(bytes,0,length));
        //拿完走羊
        ds.close();
    }
}




//组播 client
    DatagramSocket ds = new DatagramSocket();
    String s = "hello 组播";
    byte[] bytes = s.getBytes();
    InetAddress address = InetAddress.getByName("224.0.1.1");
    DatagramPacket dp = new DatagramPacket(bytes,bytes.length,address,10000);
    ds.send(dp);
    ds.close();

//server
    MulticastSocket ms = new MulticastSocket(10000);
    byte[] bytes = new byte[1024];
    DatagramPacket dp = new DatagramPacket(bytes,bytes.length );
    ms.joinGroup(InetAddress.getByName("224.0.1.1"));
    ms.receive(dp);
    int length = dp.getLength();
    System.out.println(new String(bytes,0,length));
    ms.close();

TCP


public class client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1",10000);
        OutputStream os = socket.getOutputStream();
        os.write("hello".getBytes());
        os.close();
        socket.close();
    }
}

public class server {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10000);
        Socket accept = ss.accept();
        InputStream is = accept.getInputStream();
        int i;
        while ((i = is.read()) != -1) {
            System.out.print((char) i);
        }
    }
}