简体   繁体   中英

Problem with IP selection Socket Programming C#

I am creating a server (desktop based) which listens on a port 4504 using this bit of code

                IPAddress[] AddressAr = null;
                String ServerHostName = "";

                try
                {
                    ServerHostName = Dns.GetHostName();
                    IPHostEntry ipEntry = Dns.GetHostByName(ServerHostName);
                    AddressAr = ipEntry.AddressList;
                }
                catch (Exception) { }

                if (AddressAr == null || AddressAr.Length < 1)
                {
                    return "Unable to get local address ... Error";
                }

                Listener_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                Listener_Socket.Bind(new IPEndPoint(AddressAr[0], Port));
                Listener_Socket.Listen(-1);

                Listener_Socket.BeginAccept(new AsyncCallback(EndAccept), Listener_Socket);

                return ("Listening On " + AddressAr[0].ToString() + ":" + Port + "... OK");

Now the problem is that, I want to run this on my server and the value of AddressAr[0] I want to be is the public IP of my server, but this snippet returns the local lan address of the server.

Like I want AddressAr[0] = "180.123.45.6" something [which is the public IP of my server], but with this snippet I am getting AddressAr[0] = "192.168.2.2"

PS: I am running this server as a desktop app and my trials were in the debugging mode.

I'd appreciate any help. Thank You.

When programing server, you should always listen local ip "127.0.0.1" and all your connections from outside redirect to your local ip address where server is installed.

Routing request from outside you should handle on your router. So basically that is it.

I hope this helps.

You need to listen on your local host, which will be your 192.168.2.2 (this is correct) and then forward the external packets/traffic from your public address to your local machine.

If you're using, for instance, a linksys router, you can go to NAT/QOS and forward any incoming traffic on a specific port, eg 4504 to your local machine address 192.168.2.2

Any standard home router will have port forwarding built into the firmware.

You can simply listen on any IP address that your machine has:

listenerSocket.Bind(new IPEndPoint(IPAddress.Any, port));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM