tom_at_work at yline.com
Tue Jul 16 16:13:12 CEST 2002
Subject: [fpc-pascal]Socket problems
>ListenPort is a word containing 7878
>Now, I am running as a normal user, but as root, the -S2 version runs
>without error, but does not answer on the port 7878, but on 198. (which
>explains why as a user I cannot bind to it, but why is it listening on
>198?) The htons() is from inetaux.pas, the code for which is at the end of
>this email, but if I don't have it - and I think I should (the document
>that I have learned from provided the function) - the program doesn't error
>as a user, but even an nmap scan doesn't register any new ports open.
>This is most confusing, as I'm sure you can appreciate, and any suggestions
>would be gratefully recieved.
>htons() from inetaux.pas :
>function htons(i : Integer) : Integer;
> htons := lo(i) shl 8 or hi(i);
This function is the problem. Due to different sizes of the Integer type
in the different compiler modes the htons() function returns wrong
In both -Sd and -S2 the Integer type is 32 bit, the lo() and hi()
function return the lo() and hi() - *word* (not byte) of the given
E.g. lo(7878) = 7878 and hi(7878) = 0 so htons returns 2016768 which is
likely invalid. =)
Using -St or *no* compiler mode switch solves the problem.
The reason why bind() binds to port 198 ist that the hi-byte of the low
word (which is used by bind()) of 2016768 is 198 (the low-byte is
zero).... Iirc user programs are not allowed to bind to a port < 1024
(at least your system is set up in this way), that also explains the
"permission denied" when not logged in as root.
However I don't know why the program crashes when compiled in one mode
but not in the other.... Try using the -ghl switches to get more
information about the crash location.
I recommend defining und exclusively using own integer types in your
code which are automatically mapped to types with the same value ranges
independently of the compiler mode to avoid those really nasty
Finally, here's a compiler mode independent (at least atm) version of
the htons() function:
function htons(i : Word) : Word;
htons := lo(i) shl 8 or hi(i);
Because the "Word" - type is always 16 bit unsigned integer sized in FPC
supported platforms and modes. ^^
More information about the fpc-pascal