How to determine the IdTcpServer's 'internet' ip and port using delphi? Not the local (127.0.0.1 or 192.168.0.1) but the public internet ones.
Ports and Bindings
The port number is easily determined, if you care to inspect TIdTcpServer, you'll notice it has a DefaultPort
property, and Bindings
and so if you are asking what port it is "accepting connections on", it should be the DefaultPort, or whatever is configured inside Bindings
. Once you have a session active, that session will be active on its own port number which is dynamically assigned.
If in my app, I set the IdTcpServer1.DefaultPort to 90, and then dump the contents of the bindings at runtime I get this list:
0.0.0.0:90
0:0:0:0:0:0:0:0:90
The above list showing all zeroes is IP-address-wildcard notation, telling me that I'm listening on all available local IPV4 and IPV6 addresses, at port 90. The code I used to dump the above list is:
procedure DumpBindings;
var
n:Integer;
begin
for n := 0 to IdTCPServer1.Bindings.Count-1 do begin
with IdTCPServer1.Bindings[n] do begin
Memo1.Lines.Add( ip+':'+IntToStr(Port) );
end;
end;
end;
Public Ip Addresses
So lets go back to IP addresses only, and ignore ports, for the rest of this question:
Your computer probably has an ethernet card, or a wireless network adaptor, or both, and either of both of those, could each have their own private address. Secondly, any network adapter in your computer could also have a public IP if you are the network administrator and you've given it one. If you did not configure the network you are using, chances are very slim that you're using a publically accessible IP at all on your machine.
Your question would be better if you first looked here which tells you how to determine what IPs your computer is accessible as (enumerate all local IPs). Then you could ask a question about filtering that list, and finding the correct one by discarding private non-routable addresses. Except that I bet it won't work in your case... Let's figure out why...
If you are an average home or business desktop PC user, who is using a private-IP address on your PC, and your internet connection happens via Network Address Translation (NAT), then the answer is that your PC doesn't even have a public address.
It is possible to configure a NAT based router to forward ports, but I am unaware of any way for the recipient of that forwarding to be aware of the existence of a port forward to your machine. If you need help configuring your NAT based DSL or cable modem at home to forward a port to your Delphi application, that would be a better question to ask somewhere else.
精彩评论