Search code examples
javaportrouterforwarding

Router port forwarding using cling


I'm currently developing an Match Maker for a game called GTA, the problem is that the game server uses 7777 port and I need to open this port to the world to allow players to join in the server, and I don't want the users to make any changes on their routers.

Note: The game server is not mine, I can not modify its source code, I just launch it.

So, I discovered that Cling can handle with port forwarding, but I can't make it to work!

Code I'm using:

public static void openports() throws UnknownHostException {
    InetAddress i = InetAddress.getLocalHost();
    System.out.println(i.getHostAddress());

    UpnpService upnpServiceTCP = new UpnpServiceImpl(new PortMappingListener(new PortMapping(7777, i.getHostAddress(), PortMapping.Protocol.TCP)));
    upnpServiceTCP.getControlPoint().search(new STAllHeader());

    UpnpService upnpServiceUDP = new UpnpServiceImpl(new PortMappingListener(new PortMapping(7777, i.getHostAddress(), PortMapping.Protocol.UDP)));
    upnpServiceUDP.getControlPoint().search(new STAllHeader());
}

anyone has any idea to make it work?


Solution

  • You can achieve your goal by using below code

    private void doPortForwarding() {
    
            PortMapping[] desiredMapping = new PortMapping[2];
             desiredMapping[0] = new PortMapping(8123, InetAddress.getLocalHost().getHostAddress(),
                    PortMapping.Protocol.TCP, " TCP POT Forwarding");
    
             desiredMapping[1] = new PortMapping(8123, InetAddress.getLocalHost().getHostAddress(),
                        PortMapping.Protocol.UDP, " UDP POT Forwarding");
    
    
             UpnpService upnpService = new UpnpServiceImpl();
             RegistryListener registryListener = new PortMappingListener(desiredMapping);
             upnpService.getRegistry().addListener(registryListener);
    
            upnpService.getControlPoint().search();
    
        }