DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Projections/DTOs in Spring Data R2DBC
  • Functional Interfaces in Java
  • Functional Interface Explained in Detail Introduced From Java 8
  • Smart Dependency Injection With Spring: Assignability (Part 2 of 3)

Trending

  • LTS JDK 21 Features
  • Next.js vs. Gatsby: A Comprehensive Comparison
  • Automated Testing: The Missing Piece of Your CI/CD Puzzle
  • AI for Web Devs: Project Introduction and Setup
  1. DZone
  2. Data Engineering
  3. IoT
  4. Java: Testing a Socket is Listening on All Network Interfaces/Wildcard Interface

Java: Testing a Socket is Listening on All Network Interfaces/Wildcard Interface

Mark Needham user avatar by
Mark Needham
·
Jul. 17, 13 · Interview
Like (0)
Save
Tweet
Share
11.67K Views

Join the DZone community and get the full member experience.

Join For Free

I previously wrote a blog post describing how I’ve been trying to learn more about network sockets in which I created some server sockets and connected to them using netcat.

The next step was to do the same thing in Java and I started out by writing a server socket which echoed any messages sent by the client:

public class EchoServer {
    public static void main(String[] args) throws IOException {
        int port = 4444;
        ServerSocket serverSocket = new ServerSocket(port, 50, InetAddress.getByAddress(new byte[] {0x7f,0x00,0x00,0x01}));
        System.err.println("Started server on port " + port);
 
        while (true) {
            Socket clientSocket = serverSocket.accept();
            System.err.println("Accepted connection from client: "  + clientSocket.getRemoteSocketAddress() );
 
            In  in  = new In (clientSocket);
            Out out = new Out(clientSocket);
 
            String s;
            while ((s = in.readLine()) != null) {
                out.println(s);
            }
 
            System.err.println("Closing connection with client: " + clientSocket.getInetAddress());
            out.close();
            in.close();
            clientSocket.close();
        }
    }
}
 
public final class In {
    private Scanner scanner;
 
    public In(java.net.Socket socket) {
        try {
            InputStream is = socket.getInputStream();
            scanner = new Scanner(new BufferedInputStream(is), "UTF-8");
        } catch (IOException ioe) {
            System.err.println("Could not open " + socket);
        }
    }
 
    public String readLine() {
        String line;
        try {
            line = scanner.nextLine();
        } catch (Exception e) {
            line = null;
        }
        return line;
    }
 
    public void close() {
        scanner.close();
    }
}
 
public class Out {
    private PrintWriter out;
 
    public Out(Socket socket) {
        try {
            out = new PrintWriter(socket.getOutputStream(), true);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
 
    public void close() {
        out.close();
    }
 
    public void println(Object x) {
        out.println(x);
        out.flush();
    }
}

I ran the main method of the class and this creates a server socket on port 4444 listening on the 127.0.0.1 interface and we can connect to it using netcat like so:

$ nc -v 127.0.0.1 4444
Connection to 127.0.0.1 4444 port [tcp/krb524] succeeded!
hello
hello

The output in my IntelliJ console looked like this:

Started server on port 4444
Accepted connection from client: /127.0.0.1:63222
Closing connection with client: /127.0.0.1

Using netcat is fine but what I actually wanted to do was write some test code which would check that I’d made sure the server socket on port 4444 was accessible via all interfaces i.e. bound to 0.0.0.0.

There are actually some quite nice classes in Java which make this very easy to do and wiring those together I ended up with the following client code:

public static void main(String[] args) throws IOException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface networkInterface : Collections.list(nets)) {
            for (InetAddress inetAddress : Collections.list(networkInterface.getInetAddresses())) {
                Socket socket = null;
                try {
                    socket = new Socket(inetAddress, 4444);
                    System.out.println(String.format("Connected using %s [%s]", networkInterface.getDisplayName(), inetAddress));
                } catch (ConnectException ex) {
                    System.out.println(String.format("Failed to connect using %s [%s]", networkInterface.getDisplayName(), inetAddress));
                } finally {
                    if (socket != null) {
                        socket.close();
                    }
                }
            }
        }
 
    }
}

If we run the main method of that class we’ll see the following output (on my machine at least!):

Failed to connect using en0 [/fe80:0:0:0:9afe:94ff:fe4f:ee50%4]
Failed to connect using en0 [/192.168.1.89]
Failed to connect using lo0 [/0:0:0:0:0:0:0:1]
Failed to connect using lo0 [/fe80:0:0:0:0:0:0:1%1]
Connected using lo0 [/127.0.0.1]

Interestingly we can’t even connect via the loopback interface using IPv6 which is perhaps not that surprising in retrospect given we bound using an IPv4 address.

If we tweak the second line of EchoServer from:

ServerSocket serverSocket = new ServerSocket(port, 50, InetAddress.getByAddress(new byte[] {0x7f,0x00,0x00,0x01}));

to 

ServerSocket serverSocket = new ServerSocket(port, 50, InetAddress.getByAddress(new byte[] {0x00,0x00,0x00,0x00}));

And restart the server before re-running the client we can now connect through all interfaces:

Connected using en0 [/fe80:0:0:0:9afe:94ff:fe4f:ee50%4]
Connected using en0 [/192.168.1.89]
Connected using lo0 [/0:0:0:0:0:0:0:1]
Connected using lo0 [/fe80:0:0:0:0:0:0:1%1]
Connected using lo0 [/127.0.0.1]

We can then wrap the EchoClient code into our testing framework to assert that we can connect via all the interfaces.

Interface (computing) Java (programming language) Network

Published at DZone with permission of Mark Needham, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Projections/DTOs in Spring Data R2DBC
  • Functional Interfaces in Java
  • Functional Interface Explained in Detail Introduced From Java 8
  • Smart Dependency Injection With Spring: Assignability (Part 2 of 3)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: