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
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

How are you handling the data revolution? We want your take on what's real, what's hype, and what's next in the world of data engineering.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Advanced Brain-Computer Interfaces With Java
  • Revolutionizing Network Operations With Automated Solutions: A Deep Dive Into ReactJS
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Java 21 SequenceCollection: Unleash the Power of Ordered Collections

Trending

  • Transform Settlement Process Using AWS Data Pipeline
  • Microservices for Machine Learning
  • Reinforcement Learning in CRM for Personalized Marketing
  • Essential JVM Tools for Garbage Collection Debugging
  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

By 
Mark Needham user avatar
Mark Needham
·
Jul. 17, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
12.6K 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

  • Advanced Brain-Computer Interfaces With Java
  • Revolutionizing Network Operations With Automated Solutions: A Deep Dive Into ReactJS
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Java 21 SequenceCollection: Unleash the Power of Ordered Collections

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: