smalltalkpharoseasidegnu-smalltalkpharo-5

Is there a specific way to get the Ip of a computer in Pharo smalltalk?


I am trying to run an application Pharo that requires data from the Ip of the host computer in which it's running. In general I have to open the code to set it manually in my Pharo code then launch the application. Is there a better and programmatically way of getting the IP address and returning this address automatically regardless of the computer? Say I deploy it to different computer.


Solution

  • I think you are searching for NetResolverName.

    To get name of your computer:

    NetNameResolver localHostName
    

    Then you can use it for the IP address. If you execute in Workspace:

    NetNameResolver addressForName: NetNameResolver localHostName
    

    You will get a local network address.

    In my case: #[192 168 1 17]

    Edit

    You can also directly query it via:

    NetNameResolver localAddressString
    

    Where you will get just: '192 168 1 17'

    Note: If you are getting 127.0.0.1

    If you are getting localhost address => 127.0.0.1 you probably have issues with the host mapping.
    You can test that with via ping "hostname" e.g. ping localhost.localdomain which will get you replies from 127.0.0.1. If you have correct setup (hosts, DNS, etc.) you should get reply from your IP address.

    When I have changed the hostname from localhost.localdomain to smalltalk then ping smalltalk correctly replies with 192.168.10.30. Then Pharo produces correct result.