IP,端口号,协议
public class get {
public static void main(String[] args) throws UnknownHostException {
InetAddress id = InetAddress.getByName("127.0.0.1");
System.out.println(id);
String hostName = id.getHostName();
System.out.println(hostName);
String address = id.getHostAddress();
System.out.println(address);
}
}
发送
public class demo1 {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket();
String str = new String("你好嘉宝");
byte[] bytes = str.getBytes();
InetAddress byName = InetAddress.getByName("127.0.0.1");
int port = 10086;
DatagramPacket dp = new DatagramPacket(bytes,bytes.length,byName,port);
ds.send(dp);
ds.close();
}
}
接受
public class receive {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(10086);
byte[] bytes = new byte[1024];
DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
ds.receive(dp);
byte[] data = dp.getData();
int len = dp.getLength();
InetAddress address = dp.getAddress();
int port = dp.getPort();
System.out.println("接受的数据为" + new String(data,0,len) + ",该数据的地址和接受端口1分别为" + address + "," + port);
ds.close();
}
}