---
title: "Current Interface and Random Port with Node.js"
description: "Quick way to get the current network interface and a random port for Node.js servers. Practical notes and code examples on."
url: "https://h3manth.com/scribe/current-interface-and-random-port-with-nodejs/"
canonical_url: "https://h3manth.com/scribe/current-interface-and-random-port-with-nodejs/"
markdown_url: "https://h3manth.com/scribe/blog/current-interface-and-random-port-with-nodejs.md"
publishDate: "2014-02-16T00:00:00.000Z"
author: "Hemanth HM"
category: "node"
tags: ["node","javascript"]
word_count: 131
reading_time_minutes: 1
x_markdown_tokens: 320
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Current Interface and Random Port with Node.js

> Quick way to get the current network interface and a random port for Node.js servers. Practical notes and code examples on.

Picking a random port and current interface for a Node.js server is pretty easy!

## Getting the IPv4 Address

Loop through the OS interfaces and get the IPv4:

```javascript
var IPv4 = (function() {
  var interfaces = require('os').networkInterfaces();
  var IP;
  
  for (var iface in interfaces) {
    interfaces[iface].forEach(function(addr) {
      if (addr.family == 'IPv4') {
        IP = addr.address;
      }
    });
  }
  return IP;
}());
```

## Fetching a Random Port

The trick is `server.listen(0, IPv4)` - this makes the server listen on a random available port:

```javascript
var http = require('http');
var server = http.createServer();

server.listen(0, IPv4);

server.on('listening', function() {
  console.log('Server is running on: ' + IPv4 + ':' + server.address().port);
});
```

> **Note:** In a cluster, each worker will receive the same "random" port on subsequent `listen(0)` calls after the first.
