About the author
The following Delphi code uses ICMP and SNMP to detect the dynamic IP address of your router when it is connected to a WAN.
It first gets the IP address of www.borland.com and then attempts to do a trace route to it. The trace route is only allowed to travel at most 1 hop. In a corporate environment, some changes are required in order to detect the router for the corporate environment.
Since the first hop is definitely the router's IP address, it assumes it has gotten the gateway IP address.
It then uses the SNMP protocol to discover the dynamic IP address that the router has been assigned with.
var GatewayIP, BorlandIP: string; DynamicIP, origOid: string; I: Integer; SNMP: TIdSNMP; ICMP: TIdIcmpClient;begin SNMP := TIdSNMP.Create(nil); ICMP := TIdIcmpClient.Create(nil); try // Step 1: Get the Gateway IP address // Assumes the Gateway is only 1 connection away from the machine BorlandIP := GStack.ResolveHost('www.borland.com'); ICMP.Host := BorlandIP; ICMP.TTL := 1; ICMP.ReceiveTimeout := 5000; ICMP.Ping;
GatewayIP := ICMP.ReplyStatus.FromIpAddress;
// Step 2: Query the gateway using SNMP // This assumes the gateway is the immediate connection to the Internet // or leads to a xDSL modem running in bridging mode that connects to // the Internet
SNMP.Community := 'public'; SNMP.Host := GatewayIP; SNMP.Query.Clear; origOID := '1.3.6.1.2.1.4.20.1.1'; SNMP.Query.MIBAdd(origOID, ''); SNMP.Query.PDUType := PDUGetNextRequest;
while SNMP.SendQuery do begin if Copy(SNMP.Reply.MIBOID[0], 1, Length(origOID)) <> origOID then Break;
// For each result, check that it is not the Gateway IP // If it is not, assume that it is the Dynamic IP // If a gateway has multiple IP addresses assigned, the last // IP address will be considered to be the Dynamic IP for I := 0 to SNMP.Reply.ValueCount - 1 do if SNMP.Reply.Value[I] <> GatewayIP then DynamicIP := SNMP.Reply.Value[I];
SNMP.Query.Clear; SNMP.Query.MIBAdd(SNMP.Reply.ValueOID[0], ''); SNMP.Query.PDUType := PDUGetNextRequest; end; finally ICMP.Free; SNMP.Free; end;
How to free more space on your home drive by redirecting the location for SDKs in RAD Studio
Learn the command line used to compile System.pas in Delphi
A method to design records so that they're allocated on a specific byte boundary, such as 16 bytes, 512 bytes, 4096 bytes, etc.
Learn why the map is cool in Go!