[macos] Virtual network interface in Mac OS X

I know that you can make a virtual network interface in Windows (see here), and in Linux it is also pretty easy with ip-aliases, but does something similar exist for Mac OS X? I've been looking for loopback adapters, virtual interfaces and couldn't find a good solution.

You can create a new interface in the networking panel, based on an existing interface, but it will not act as a real fully functional interface (if the original interface is inactive, then the derived one is also inactive).

This scenario is needed when working in a completely disconnected situation. Even then, it makes sense to have networking capabilities when running servers in a VMWare installation. Those virtual machines can be reached by their IP address, but not by their DNS name, even if I run a DNS server in one of those virtual machines. By configuring an interface to use the virtual DNS server, I thought I could test some DNS scenario's. Unfortunately, no interface is resolving DNS names if none of them are inactive...

This question is related to macos networking

The answer is


The loopback adapter is always up.

ifconfig lo0 alias 172.16.123.1 will add an alias IP 172.16.123.1 to the loopback adapter

ifconfig lo0 -alias 172.16.123.1 will remove it


Replying in particular to:

You can create a new interface in the networking panel, based on an existing interface, but it will not act as a real fully functional interface (if the original interface is inactive, then the derived one is also inactive).

This can be achieved using a Tun/Tap device as suggested by psv141, and manipulating the /Library/Preferences/SystemConfiguration/preferences.plist file to add a NetworkService based on either a tun or tap interface. Mac OS X will not allow the creation of a NetworkService based on a virtual network interface, but one can directly manipulate the preferences.plist file to add the NetworkService by hand. Basically you would open the preferences.plist file in Xcode (or edit the XML directly, but Xcode is likely to be more fool-proof), and copy the configuration from an existing Ethernet interface. The place to create the new NetworkService is under "NetworkServices", and if your Mac has an Ethernet device the NetworkService profile will also be under this property entry. The Ethernet entry can be copied pretty much verbatim, the only fields you would actually be changing are:

  • UUID
  • UserDefinedName
  • IPv4 configuration and set the interface to your tun or tap device (i.e. tun0 or tap0).
  • DNS server if needed.

Then you would also manipulate the particular Location you want this NetworkService for (remember Mac OS X can configure all network interfaces dependent on your "Location"). The default location UUID can be obtained in the root of the PropertyList as the key "CurrentSet". After figuring out which location (or set) you want, expand the Set property, and add entries under Global/IPv4/ServiceOrder with the UUID of the new NetworkService. Also under the Set property you need to expand the Service property and add the UUID here as a dictionary with one String entry with key __LINK__ and value as the UUID (use the other interfaces as an example).

After you have modified your preferences.plist file, just reboot, and the NetworkService will be available under SystemPreferences->Network. Note that we have mimicked an Ethernet device so Mac OS X layer of networking will note that "a cable is unplugged" and will not let you activate the interface through the GUI. However, since the underlying device is a tun/tap device and it has an IP address, the interface will become active and the proper routing will be added at the BSD level.

As a reference this is used to do special routing magic.

In case you got this far and are having trouble, you have to create the tun/tap device by opening one of the devices under /dev/. You can use any program to do this, but I'm a fan of good-old-fashioned C myself:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
   int fd = open("/dev/tun0", O_RDONLY);
   if (fd < 0)
   {
      printf("Failed to open tun/tap device. Are you root? Are the drivers installed?\n");
      return -1;
   }
   while (1)
   {
      sleep(100000);
   }
   return 0;
}

In regards to @bmasterswizzle's BRILLIANT answer - more specifically - to @DanRamos' question about how to force the new interface's link-state to "up".. I use this script, of whose origin I cannot recall, but which works fabulously (in coordination with @bmasterswizzles "Mona Lisa" of answers)...

#!/bin/zsh

[[ "$UID" -ne "0" ]] && echo "You must be root. Goodbye..." && exit 1
echo "starting"
exec 4<>/dev/tap0
ifconfig tap0 10.10.10.1 10.10.10.255
ifconfig tap0 up
ping -c1 10.10.10.1
echo "ending"
export PS1="tap interface>"
dd of=/dev/null <&4 & # continuously reads from buffer and dumps to null

I am NOT quite sure I understand the alteration to the prompt at the end, or...

dd of=/dev/null <&4 & # continuously reads from buffer and dumps to null

but WHATEVER. it works. link light: green?. loves it.

enter image description here


A few others seemed to hint at this, but the following demonstrates using ifconfig to create a vlan and test DNS on the virtual interface (using minidns) on OS X 10.9.5:

$ sw_vers -productVersion
10.9.5
$ sudo ifconfig vlan169 create && echo vlan169 created
vlan169 created
$ sudo ifconfig vlan169 inet 169.254.169.254 netmask 255.255.255.255 && echo vlan169 configured
vlan169 configured
$ sudo ./minidns.py 169.254.169.254 &
[1] 35125
$ miniDNS :: * 60 IN A 169.254.169.254


$ dig @169.254.169.254 +short test.host
Request: test.host. -> 169.254.169.254
Request: test.host. -> 169.254.169.254
169.254.169.254
$ sudo kill 35125
$ 
[1]+  Exit 143                sudo ./minidns.py 169.254.169.254
$ sudo ifconfig vlan169 destroy && echo vlan169 destroyed
vlan169 destroyed

It's possible to use TUN/TAP device. http://tuntaposx.sourceforge.net/


if you are on a dev environment and want access some service already running on localhost/host machine. in docker for mac you have another option.use docker.for.mac.localhost instead of localhost in docker container. docker.for.mac.host.internal should be used instead of docker.for.mac.localhost from Docker Community Edition 17.12.0-ce-mac46 2018-01-09. this allows you to connect to service running on your on mac from within a docker container.please refer below links

understanding the docker.for.mac.localhost behavior

release notes


Take a look at this tutorial, it's for FreeBSD but also applies to OS X. http://people.freebsd.org/~arved/vlan/vlan_en.html


What do you mean by

"but it will not act as a real fully functional interface (if the original interface is inactive, then the derived one is also inactive"

?

I can make a new interface, base it on an already existing one, then disable the existing one and the new one still works. Making a second interface does however not create a real interface (when you check with ifconfig), it will just assign a second IP to the already existing one (however, this one can be DHCP while the first one is hard coded for example).

So did I understand you right, that you want to create an interface, not bound to any real interface? How would this interface then be used? E.g. if you disconnect all WLAN and pull all network cables, where would this interface send traffic to, if you send traffic to it? Maybe your question is a bit unclear, it might help a lot if rephrase it, so it's clear what you are actually trying to do with this "virtual interface" once you have it.

As you mentioned "alias IP" in your question, this would mean an alias interface. But an alias interface is always bound to a real interface. The difference is in Linux such an interface really IS an interface (e.g. an alias interface for eth0 could be eth1), while on Mac, no real interface is created, instead a virtual interface is created, that can configured and used independently, but it is still the same interface physically and thus no new named interface is generated (you just have two interfaces, that are both in fact en0, but both can be enabled/disabled and configured independently).


Go to Network Preferences.

At the bottom of the list of network adapters, click the + icons

Select the existing interface that you want to arp (say Ethernet 1), and give the Service Name that you want for the new port (say Ethernet 1.1) then press create.

Now you have the new virtual interface in the gui and can manage IP addresses etc it in the normal way.

ifconfig -a will confirm that you have multiple IPs on the interface, and these will still be there when you reboot.

Its a Mac. Don't fight it, do it the easy way.


i have resorted to running PFSense, a BSD based router/firewall to achieve this goal….

why? because OS X Server gets so FREAKY without a Static IP…

so after wrestling with it for DAYS to make NAT and DHCP and firewall and …

I'm trying this is parallels…

will let ya know how it goes...


ifconfig interfacename create will create a virtual interface,


Here's a good guide: https://web.archive.org/web/20160301104014/http://gerrydevstory.com/2012/08/20/how-to-create-virtual-network-interface-on-mac-os-x/

Basically you select a network adapter in the Networks pane of system preferences, then click the gear to "Duplicate Service". After the service is duplicated, you manually assign an IP in one of the private address ranges. Then ping it to make sure ;)


ifconfig interfacename create will create a virtual interface,


Questions with macos tag:

Problems with installation of Google App Engine SDK for php in OS X dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac Could not install packages due to an EnvironmentError: [Errno 13] How do I install Java on Mac OSX allowing version switching? Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Can't compile C program on a Mac after upgrade to Mojave You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user) How can I install a previous version of Python 3 in macOS using homebrew? Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'" Cannot connect to the Docker daemon on macOS Stuck at ".android/repositories.cfg could not be loaded." How to switch Python versions in Terminal? Class JavaLaunchHelper is implemented in two places How can I add a .npmrc file? "SSL certificate verify failed" using pip to install packages How to uninstall Anaconda completely from macOS mysqli_real_connect(): (HY000/2002): No such file or directory How do I upgrade to Python 3.6 with conda? pip or pip3 to install packages for Python 3? Brew install docker does not include docker engine? Homebrew refusing to link OpenSSL How to install JQ on Mac by command-line? How to update Ruby with Homebrew? psql: command not found Mac macOS on VMware doesn't recognize iOS device Is there a keyboard shortcut (hotkey) to open Terminal in macOS? pip installs packages successfully, but executables not found from command line SSL: CERTIFICATE_VERIFY_FAILED with Python3 Eclipse not recognizing JVM 1.8 How to install latest version of openssl Mac OS X El Capitan How can I easily switch between PHP versions on Mac OSX? Switch between python 2.7 and python 3.5 on Mac OS X Finding Android SDK on Mac and adding to PATH How to install wget in macOS? Reset MySQL root password using ALTER USER statement after install on Mac `node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX MacOS Xcode CoreSimulator folder very big. Is it ok to delete content? Mysql password expired. Can't connect What version of Python is on my Mac? How to install gdb (debugger) in Mac OSX El Capitan? Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave Operation Not Permitted when on root - El Capitan (rootless disabled) How to run C program on Mac OS X using Terminal? How to install sshpass on mac? Can't install gems on OS X "El Capitan" "OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection) Can you install and run apps built on the .NET framework on a Mac? Pyspark: Exception: Java gateway process exited before sending the driver its port number pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

Questions with networking tag:

Access HTTP response as string in Go Communication between multiple docker-compose projects Can't access 127.0.0.1 How do I delete virtual interface in Linux? ConnectivityManager getNetworkInfo(int) deprecated Bridged networking not working in Virtualbox under Windows 10 Difference between PACKETS and FRAMES How to communicate between Docker containers via "hostname" java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused) wget: unable to resolve host address `http' How can I use iptables on centos 7? How can I kill whatever process is using port 8080 so that I can vagrant up? Throughput and bandwidth difference? How can I get the IP address from NIC in Python? Chrome hangs after certain amount of data transfered - waiting for available socket ping response "Request timed out." vs "Destination Host unreachable" Accessing a local website from another computer inside the local network in IIS 7 Find UNC path of a network drive? The network path was not found Sending string via socket (python) Default SQL Server Port ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known How do I get Flask to run on port 80? How to allow remote access to my WAMP server for Mobile(Android) How to redirect DNS to different ports Checking host availability by using ping in bash scripts Propagation Delay vs Transmission delay Forward host port to docker container How to set the timeout for a TcpClient? Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley Volley - POST/GET parameters OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"? Fastest way to ping a network range and return responsive hosts? How to get a list of all valid IP addresses in a local network? What are the retransmission rules for TCP? The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) What is the functionality of setSoTimeout and how it works? How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error? Copy files to network computers on windows command line How do I increase the RAM and set up host-only networking in Vagrant? How can I debug what is causing a connection refused or a connection time out? Multiple ping script in Python Command line for looking at specific port How to ping ubuntu guest on VirtualBox How to monitor network calls made from iOS Simulator DNS caching in linux trace a particular IP and port Best TCP port number range for internal applications Java socket API: How to tell if a connection has been closed?