From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.5-pre1 (2020-06-20) on ip-172-31-74-118.ec2.internal X-Spam-Level: X-Spam-Status: No, score=-1.9 required=3.0 tests=BAYES_00 autolearn=ham autolearn_force=no version=3.4.5-pre1 Date: 21 Jul 93 18:50:16 GMT From: emery@mitre-bedford.arpa (David Emery) Subject: Re: SunAda question Message-ID: List-Id: >procedure gethost is > namelen : integer := 20; > hostname : string (1..namelen); > stat : unix.status_code; >begin > stat := unix.gethostname(hostname'address,namelen); > text_io.put_line ("Hostname is " & hostname); >end gethost; First, this code is not portable across compilers. In particular, it 'just happens to work' on Verdix that string'address is the same as string(string'first)'address. The address passed to C must be the address of the first element of the string. String'address is not well-defined, but string(string'first)'address -is- defined to be the address of the first element of the string. On some compilers, string'address may return the address of the 'dope vector' for the string, or something else besides the address of the first element. Another problem with this code is that it presumes the length of the hostname is -exactly- 20 characters. If the hostname is greater than 20, it will be truncated by the C/Unix operation gethostname(). If it is less than 20, then you'll have garbage after the end of the string, marked by Ascii.nul. Furthermore, this code perpetuates the C tradition by completely ignoring the error return, which means that the data in hostname will be undefined if the function failed. Try this: with System; function Hostname return string -- will return "" on any error is maxnamelen : integer := 2048; -- much safer value than 20! buffer : string (1..namelen) := (others => Ascii.nul); -- essentially a Zero-length C string subtype int is integer; -- assuming C's int = integer status : int; stringlength : int; -- C function prototype for gethostname: -- int gethostname(name, namelen) -- char *name; -- int namelen; -- returns 0 on success, -1 on failure. function gethostname (addr : System.address; length : int) return int; pragma interface (C, gethostname); -- C function prototype for strlen: -- int strlen (str); -- char * addr; -- returns the length of the string, not including the null at the -- end of the string. Can return 0. function strlen (addr : System.address) return int; pragma interface (C, strlen); begin status := gethostname(buffer(buffer)'address, maxnamelen); if status = 0 then stringlength := strlen (buffer(buffer)'address); return buffer(buffer'first .. buffer'first + stringlength - 1 ); else return ""; -- empty string on any error end if; end Hostname; dave