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();
}
}
该文章展示了两个Java程序,一个用于发送UDP数据包到指定IP和端口,另一个用于接收数据。程序使用了InetAddress和DatagramSocket类,涉及IP地址、主机名、端口号以及数据包的创建和发送过程。
1600

被折叠的 条评论
为什么被折叠?



