Selected Reading
Java.net.DatagramPacket.getPort() Method
Description
The java.net.DatagramPacket.getPort() returns the port number on the remote host to which this datagram is being sent or from which the datagram was received.
Declaration
Following is the declaration for java.net.DatagramPacket.getPort() method
public int getPort()
Parameters
NA
Return Value
This method returns the port number on the remote host to which this datagram is being sent or from which the datagram was received.
Exception
NA
Example
The following example shows the usage of net.DatagramPacket.getPort() method
package com.tutorialspoint;
import java.net.*;
class DatagramPacketDemo {
public static void main(String args[]) throws Exception {
// create a DatagramSocket object binded to port 9999
DatagramSocket ds = new DatagramSocket(9999);
// create a byte array buf
byte buf[] = new byte[100];
// create a DatagramPacket object
DatagramPacket dp = new DatagramPacket(buf, buf.length);
// recieve the datagram packet into dp
ds.receive(dp);
// create an int object p, which stores port number
int p = dp.getPort();
// print p value
System.out.println("Port number is : " + p );
}
}
Let us compile and run the above program, this will produce the following result:
Port number is : 4499
Advertisements