Monday, March 2, 2020

Get My IP With Delphi Programming

Get My IP With Delphi Programming Internet this and internet that. Everybody wants to be on the internet nowadays. Everyone wants to program internet nowadays. One of the most interesting tasks when starting to code for the internet is how to obtain the IP address of a computer connected to the internet. IP? TCP? Simply technical: the internet is built on TCP/IP connections. The TCP part describes how two computers set up a connection to each other and transfer data. The IP part primarily deals with how to get a message routed across the internet. Each connected machine has a unique IP address that allows others to figure out a path to any computer around the world wide web (or the world precisely). Uses Winsock To obtain the IP address of the computer you are using when connected to the internet, we need to call some of the API functions *defined* in the Winsock unit. Well create a GetIPFromHost function that calls several Winsock API functions in order to get the IP. Before we can even use WinSock functions, we must have a valid session. This session is created with the WinSock WSAStartup function. At the end of our function, a call to SAC leanup is made in order to terminate the use of the Windows Sockets APIs. To obtain the computers IP address, we must use GetHostByName in conjunction with GetHostName. Each computer is called a host and we can get the hostname with a special function call: GetHostName. We then use GetHostByName to get the IP-address, related to this hostname. Get IP Delphi.Project.Code Start Delphi and place one Button and two Edit boxes on a newly created Form. Add the GetIPFromHost  function to the implementation part of your unit and assign the following code to the OnClick event handler of a button (below): uses Winsock; function GetIPFromHost(var HostName, IPaddr, WSAErr: string): Boolean; type Name array[0..100] of Char; PName ^Name; var HEnt: pHostEnt; HName: PName; WSAData: TWSAData; i: Integer; begin Result : False; if WSAStartup($0101, WSAData) 0 then begin WSAErr : Winsock is not responding.; Exit; end; IPaddr : ; New(HName); if GetHostName(HName^, SizeOf(Name)) 0 thenbegin HostName : StrPas(HName^); HEnt : GetHostByName(HName^); for i : 0 to HEnt^.h_length - 1 do IPaddr : Concat(IPaddr, IntToStr(Ord(HEnt^.h_addr_list^[i])) .); SetLength(IPaddr, Length(IPaddr) - 1); Result : True; end else begin case WSAGetLastError of WSANOTINITIALISED:WSAErr:WSANotInitialised; WSAENETDOWN :WSAErr:WSAENetDown; WSAEINPROGRESS :WSAErr:WSAEInProgress; end; end; Dispose(HName); WSACleanup; end; procedure TForm1.Button1Click(Sender: TObject); var Host, IP, Err: string; begin if GetIPFromHost(Host, IP, Err) then begin Edit1.Text : Host; Edit2.Text : IP; end else M essageDlg(Err, mtError, [mbOk], 0); end;

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.