-2

The following code returns the IP address of the first TCP/IP connection for a machine.

uses WinSock;

// ...
function GetLocalIP() : String;
var
    addr: TSockAddrIn;
    phe: PHostEnt;
    szHostName: array[0..128] of Char;
    socketData: TWSADATA;
begin
    Result := '127.0.0.1';

    // Initialize the socket API
    if (WSAStartup($101, socketData) = 0) then
        begin
        // Get local machine name
        if (GetHostName(szHostName, 128) = SOCKET_ERROR) then
            Exit;

        // Use name to find IP address
        phe := GetHostByName(szHostName);
        if (phe = nil) then
            Exit;

        addr.sin_addr.S_addr := Longint(PLongint(phe^.h_addr_list^)^);

        // Convert IP address to PChar format
        Result := inet_ntoa(addr.sin_addr);
        end;
end;

// ...
Label1.Caption :=  GetLocalIP();

What modifications would I need to make to get the IP address for all TCP/IP network connections (where there was more than one)?

I did stumble across this across this related article: Get information about the installed network adapters which appears to use a different technique using the Windows API "GetAdaptersInfo"...is this the way to go?

Community
  • 1
  • 1
AlainD
  • 5,413
  • 6
  • 45
  • 99
  • 1
    The code shown does not get the IP of *any* TCP connection. It simply performs a reverse DNS lookup using the local machine's hostname. – Remy Lebeau Mar 15 '15 at 23:33
  • Your code is missing a call to [WSACleanup](https://msdn.microsoft.com/en-us/library/windows/desktop/ms741549%28v=vs.85%29.aspx) – EProgrammerNotFound Mar 16 '15 at 02:18
  • @EProgrammerNotFound: Aah yes, well spotted. I've inherited this project and found the code as given. As Remy points out, its not the way to go about this...just trying to improve it. Thanks. – AlainD Mar 16 '15 at 14:43
  • For anyone who is looking to implement this in Delphi 7, you will need to find the definitions for IP_ADAPTER_INFO and other required structures. This site was a big help: http://www.magsys.co.uk/delphi/ – AlainD Mar 17 '15 at 16:39

1 Answers1

5

If you want to enumerate the local machine's current available IP addresses, use GetAdaptersInfo() or GetAdaptersAddresses().

If you want to enumerate the local machine's current active TCP/IP socket connections, use GetTcpTable() or GetTcpTable2() for IPv4 connections, and GetTcp6Table() or GetTcp6Table2() for IPv6 connections.

mjn
  • 36,362
  • 28
  • 176
  • 378
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Needed to manually define IP_ADAPTER_INFO and other required structures for Delphi 7...but have finally got it working. Thanks again. – AlainD Mar 17 '15 at 16:37