C++ Sockets with Router

2019-07-27 11:13发布

I'm making a multiplayer game using sockets and I have some problems with the server side.The server shall be run from my computer which is behind a router. Therefore I'm a little bit stuck with what should the server inet_addr be. I am using port 1234 and I forwarded it to my PC ( the place where I keep the server ).

Port forwarding

I have tried using my own ip address which i got from myipaddress.com, also my computer's router address ( 192.168.0.101 ). The first try i was getting A LOT of connections which ended up in killing the program and in the second try nothing connects to it.

addr.sin_addr.s_addr= inet_addr("192.168.0.101");
addr.sin_port       = htons(1234);
addr.sin_family = AF_INET;

What should I do in order to make any client be able to connect to the server and the server to run from behind the router ?

标签: c++ sockets port
2条回答
孤傲高冷的网名
2楼-- · 2019-07-27 11:38

With port forwarding in your router, the router needs to know which device to send packets directed at the selected port range to. The router is asking for your internal IP address, (websites only see your external IP address).

You can find this on Windows by calling ipconfig in cmd (I believe the command may be ifconfig -a on Linux), this lists all of your network interfaces and your internal IP address on any that are connected. You should look for a value in the form 192.168.0.xxx.

When someone then wants to connect to your server if you give them your external IP address and desired port, their packet will be sent to your router on that port, and it will forward it to your computer at the internal IP address.

If you disconnect your computer from the network regularly you may need to configure your internal IP so that it is static and always allocated the same address.

查看更多
Animai°情兽
3楼-- · 2019-07-27 11:52

This has nothing to do with your program, and everything to do with your network configuration. Go learn about NAT (network address translation) and doing port forwarding or DMZ on your router.

Usually you want your program to bind to all interfaces - INADDR_ANY - but the important one is the address on the network controlled by your router (often 192.168.0.0/16, but it can be any RFC1918 address block).

Once you have your network configured on your router and binding the external interface from your program (don't hard code an address like in your example, just use INADDR_ANY)

serv_addr.sin_addr.s_addr = inet_addr(INADDR_ANY);
查看更多
登录 后发表回答