Network kit: fundamentals

Network kit: fundamentals

  • mdo  DigitalBox
  •   KitLab
  •   April 20, 2026

In previous KitLab articles, we explored various Haiku kits: Application, Interface, Translation, Storage, Locale, and Support.

Now, let's dive into networking with the Network Kit!

Haiku's Network Kit provides the tools you need to build networked applications: from simple hostname lookups to complex client-server architectures.

For this article, we'll start with the fundamentals: working with network addresses and resolving hostnames.

Understanding BNetworkAddress

The BNetworkAddress class represents a network address (IP address + port).

It handles both IPv4 and IPv6 addresses seamlessly.

You can create a BNetworkAddress in several ways:

// Empty address
BNetworkAddress addr;

// From hostname and port
BNetworkAddress addr("www.haiku-os.org", 80);

// From IP string and port
BNetworkAddress addr("192.168.1.1", 8080);

// From another BNetworkAddress
BNetworkAddress addr2(addr);

The class takes care of the low-level socket address structures (sockaddr_in, sockaddr_in6) for you.

Basic Address Operations

Once you have a BNetworkAddress, you can:

Check if resolution succeeded:

BNetworkAddress addr("www.haiku-os.org", 80);
if (addr.InitCheck() == B_OK) {
    // Address is valid
}

Get the IP address as a string:

BString ipString = addr.ToString(false);  // false = without port
printf("IP: %s\n", ipString.String());

Get the port:

uint16 port = addr.Port();
printf("Port: %d\n", port);

Get hostname and service name:

BString hostname = addr.HostName();
BString service = addr.ServiceName();

Example: HostLookup.cpp

Here's a simple program that resolves a hostname to its IP address:

#include <Application.h>
#include <Window.h>
#include <Button.h>
#include <TextControl.h>
#include <StringView.h>
#include <LayoutBuilder.h>
#include <NetworkAddress.h>
#include <String.h>
#include <stdio.h>

class LookupWindow : public BWindow {
public:
    LookupWindow()
        : BWindow(BRect(100, 100, 500, 250), "Host Lookup",
                  B_TITLED_WINDOW, B_QUIT_ON_WINDOW_CLOSE | B_AUTO_UPDATE_SIZE_LIMITS)
    {
        fHostInput = new BTextControl("Host:", "www.haiku-os.org", NULL);
        fLookupButton = new BButton("lookup_btn", "Lookup", new BMessage('look'));
        fResultLabel = new BStringView("result", "Enter a hostname and click Lookup");

        BLayoutBuilder::Group<>(this, B_VERTICAL, B_USE_DEFAULT_SPACING)
            .SetInsets(B_USE_WINDOW_SPACING)
            .Add(fHostInput)
            .Add(fLookupButton)
            .Add(fResultLabel)
            .AddGlue()
            .End();

        fLookupButton->SetTarget(this);
        Show();
    }

    void MessageReceived(BMessage* msg) override {
        if (msg->what == 'look') {
            PerformLookup();
        } else {
            BWindow::MessageReceived(msg);
        }
    }

    bool QuitRequested() override {
        be_app->PostMessage(B_QUIT_REQUESTED);
        return true;
    }

private:
    void PerformLookup() {
        const char* hostname = fHostInput->Text();

        if (strlen(hostname) == 0) {
            fResultLabel->SetText("Please enter a hostname");
            return;
        }

        // Create a BNetworkAddress and resolve the hostname
        BNetworkAddress addr(hostname, 80);

        if (addr.InitCheck() == B_OK) {
            // Get IP address as string (without port)
            BString ipString = addr.ToString(false);

            BString result;
            result << hostname << " resolves to: " << ipString;
            fResultLabel->SetText(result.String());
            printf("Lookup successful: %s -> %s\n", hostname, ipString.String());
        } else {
            BString error;
            error << "Failed to resolve: " << hostname;
            fResultLabel->SetText(error.String());
            printf("Lookup failed for: %s\n", hostname);
        }
    }

    BTextControl*  fHostInput;
    BButton*       fLookupButton;
    BStringView*   fResultLabel;
};

class LookupApp : public BApplication {
public:
    LookupApp()
        : BApplication("application/x-vnd.demo-hostlookup") {}

    void ReadyToRun() override {
        new LookupWindow();
    }
};

int main() {
    LookupApp app;
    app.Run();
    return 0;
}

How It Works

The below features are available:

  • User Input: The BTextControl lets the user enter a hostname (e.g., "www.haiku-os.org").
  • Address Resolution: When the "Lookup" button is clicked, we create a BNetworkAddress with the hostname. The constructor automatically performs DNS resolution.
  • Display Result: We retrieve the IP address as a string using ToString(false) (the false parameter excludes the port) and display it in the BStringView.
  • Error Handling: If the resolution fails (invalid hostname, no network connection), InitCheck() returns an error status.

Compile and Run

g++ HostLookup.cpp -o HostLookup -lbe -lbnetapi

Launch the application:

./HostLookup

The window appears with a text field pre-filled with "www.haiku-os.org".

Click "Lookup" to see the resolved IP address!

Now try different hostnames and check the results:

  • www.google.com
  • github.com
  • 127.0.0.1 (localhost)

What about trying an invalid hostname ? 

As you can see the error handling is working fine:)

Working with Ports

Network addresses aren't just IP addresses — they also include port numbers.

Here's how to work with them:

// Create address with port 80 (HTTP)
BNetworkAddress webAddr("www.haiku-os.org", 80);

// Get the port
uint16 port = webAddr.Port();
printf("Port: %d\n", port);

// Create address with different port (HTTPS)
BNetworkAddress secureAddr("www.haiku-os.org", 443);

// Display with port included
BString addrWithPort = secureAddr.ToString(true);  // true = include port
printf("Address: %s\n", addrWithPort.String());

Common port numbers:

  • HTTP: 80
  • HTTPS: 443
  • FTP: 21
  • SSH: 22
  • Custom services: typically 1024-65535

IPv4 vs IPv6

BNetworkAddress handles both IPv4 and IPv6 transparently.

You can check which family an address belongs to:

BNetworkAddress addr("www.haiku-os.org", 80);

if (addr.InitCheck() == B_OK) {
    int family = addr.Family();

    if (family == AF_INET) {
        printf("This is an IPv4 address\n");
    } else if (family == AF_INET6) {
        printf("This is an IPv6 address\n");
    }
}

Additional Useful Methods

BNetworkAddress provides several helper methods for common networking tasks.

You can check the address types:

if (addr.IsLocal()) {
    printf("This is a local address\n");
}

if (addr.IsBroadcast()) {
    printf("This is a broadcast address\n");
}

if (addr.IsMulticast()) {
    printf("This is a multicast address\n");
}

Or create special addresses:

// Loopback address (127.0.0.1 or ::1)
BNetworkAddress loopback;
loopback.SetToLoopback(AF_INET, 8080);

// Wildcard address (0.0.0.0 or ::) - for servers
BNetworkAddress wildcard;
wildcard.SetToWildcard(AF_INET, 3000);

// Broadcast address
BNetworkAddress broadcast;
broadcast.SetToBroadcast(AF_INET, 9999);

Why It Matters

  • Abstraction: BNetworkAddress hides the complexity of socket addresses and handles both IPv4 and IPv6.
  • DNS Resolution: Automatic hostname-to-IP conversion without manual DNS queries.
  • Foundation: These concepts are essential for all network programming — clients and servers alike.

Try This

Now that you understand BNetworkAddress basics, here are some experiments:

  • Add reverse lookup: Display the hostname using HostName() method when you enter an IP address.
  • Display address family: Show whether the resolved address is IPv4 or IPv6 using Family().
  • Add a history list: Store previous lookups in a BListView so users can see their query history.
  • Show port information: Modify the program to let users specify a port number and display the complete address with port.
  • Multiple addresses: Some hostnames resolve to multiple IP addresses. Research how to retrieve all addresses for a given hostname (hint: look at the lower-level getaddrinfo() function).

What's Next?

In the next KitLab article, we'll build on this foundation and explore TCP communication with BNetEndpoint.

We'll create both a client and a server that can exchange data over the network.

Stay tuned — and keep on exploring!


Powered by Bludit - Hosted by Planet Hoster
© 2025 Haiku Insider