PCP request to router (port forwarding) problem.
Hi and thank you for opening this post and considering helping me,...I want my application to "forward" a port for TCP traffic, tho till now I've been using UpNP which, from what I found out is pretty insecure and it does not work always due to it being disabled, so I wanted to attempt to do the port forwarding via PCP, but for the UpNP I used the mono.nat library so it was pretty easy to get around and that's why I don't get how to construct the message. I found the documentation and the passage that contains the format of how the message is supposed to be formatted like, tho I have no idea how to do do that in C#, should I use mappings or perhaps sockets? ...and how to implement.
2 Replies
you'd use a socket to connect to the router in order to send the control messages
// Create a socket for UDP communication with the PCP server
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// Set the PCP server address and port
IPAddress serverAddress = IPAddress.Parse("192.168.1.100");
int serverPort = 65536; // PCP port
// Create a request packet
byte[] requestPacket = new byte[128];
// Set the request opcode
requestPacket[0] = 0x06; // MAP opcode
// Set the requested lifetime in seconds
requestPacket[4] = 0; // 0 seconds (delete)
// Set the protocol
requestPacket[8] = 17; // TCP protocol
// Set the internal port
requestPacket[12] = 0; // All ports
// Set the suggested external port
requestPacket[14] = 0;
socket.SendTo(requestPacket, requestPacket.Length, SocketFlags.None, serverAddress, serverPort);
// Receive the response packet from the PCP server
byte[] responsePacket = new byte[128];
int bytesReceived = socket.ReceiveFrom(responsePacket, responsePacket.Length, SocketFlags.None, ref serverAddress, ref serverPort);
// Parse the response packet
int lifetime = responsePacket[4]; // Lifetime in seconds
int protocol = responsePacket[8]; // Protocol
int internalPort = responsePacket[12]; // Internal port
byte[] assignedExternalPort = new byte[2];
Array.Copy(responsePacket, 14, assignedExternalPort, 0, 2); // Assigned external port (2 bytes)
byte[] assignedExternalIPAddress = new byte[16];
Array.Copy(responsePacket, 16, assignedExternalIPAddress, 0, 16); // Assigned external IP address (16 bytes)
does this look right?