RingDotNetfor Ring

Network tools

IP addresses, names, ping, network interfaces and "is this port open?" — the classes behind everyday network tools. Everything in this lesson runs on your own computer, so it works without internet.

What you will learn#

The program#

samples/UsingDotNet/tutorials/ch07_network_tools.ring
# network tools - IP addresses, DNS, ping, network interfaces and checking whether a port is open (all on this computer)
load "dotnet.ring"

using {
	"System"
	"System.Net"
	"System.Net.Sockets"
	"System.Net.NetworkInformation"
}

func main

	# 1. IPAddress parses an address and knows its family. A method with an "out" parameter returns a list: [success, the address].
	oParser = new IPAddress()
	oAddress = oParser.Parse("192.168.1.20")
	cBytes = oAddress.GetAddressBytes()                                  # the 4 bytes of an IPv4 address (a byte[] is a Ring text)
	? "1. " + oAddress.ToString() + " is " + oAddress.AddressFamily + ", " + len(cBytes) + " bytes, the first is " + ascii(cBytes[1])
	aGood = oParser.TryParse("10.0.0.7")
	aBad = oParser.TryParse("999.1.1.1")
	? "   TryParse('10.0.0.7'): " + yesNo(aGood[1]) + ", TryParse('999.1.1.1'): " + yesNo(aBad[1])
	oV6 = oParser.Parse("::1")
	? "   '::1' is " + oV6.AddressFamily + ", loopback: " + yesNo(oParser.IsLoopback(oV6))
	? "   private address 192.168.1.20 is not the loopback: " + yesNo(not oParser.IsLoopback(oAddress))

	# 2. An address plus a port is an IPEndPoint.
	oEndPoint = new IPEndPoint(oAddress,8080)
	? nl + "2. the endpoint " + oEndPoint.ToString() + ": address " + oEndPoint.Address.ToString() + ", port " + oEndPoint.Port

	# 3. DNS: names to addresses. "localhost" is always known, also without a network.
	oHost = new Dns().GetHostEntry("localhost")
	aAddresses = oHost.AddressList.toList()
	? nl + "3. localhost has " + len(aAddresses) + " address(es); the first is a loopback address: " + yesNo(oParser.IsLoopback(aAddresses[1]))

	# 4. Ping: an ICMP echo. The reply has a status and the round trip time in milliseconds.
	oPing = new Ping()
	oReply = oPing.Send("127.0.0.1")
	? nl + "4. ping 127.0.0.1: " + oReply.Status + ", the answer came from " + oReply.Address.ToString() + ", fast (under 100 ms): " + yesNo(oReply.RoundtripTime < 100)
	oPing.Dispose()

	# 5. The network interfaces of this computer (the types are text: Ethernet, Wireless80211, Loopback...)
	aInterfaces = new NetworkInterface().GetAllNetworkInterfaces().toList()
	lLoopback = False
	for oInterface in aInterfaces
		if oInterface.NetworkInterfaceType = "Loopback"
			lLoopback = True
		ok
	next
	? nl + "5. the computer has network interfaces: " + yesNo(len(aInterfaces) > 0) + "; one of them is the loopback: " + yesNo(lLoopback)

	# 6. Is a port open? Start a listener on a free port: connecting works. Connect to a port where nobody listens: it is refused.
	oListener = new TcpListener(oParser.Loopback,0)
	oListener.Start(NULL)
	nOpenPort = oListener.LocalEndpoint.Port
	? nl + "6. a listener is on a port that the system chose: port is open = " + yesNo(portIsOpen("127.0.0.1",nOpenPort))
	oListener.Stop()
	? "   after Stop the same port is open = " + yesNo(portIsOpen("127.0.0.1",nOpenPort))

# true when a TCP connection to the address and port is accepted within half a second
func portIsOpen cAddress, nPort

	oClient = new TcpClient()
	lOpen = False
	try
		oTask = oClient.ConnectAsync([ :host = cAddress, :port = nPort ])
		lOpen = oTask.Wait(500) and oClient.Connected
	catch
		lOpen = False                          # refused or failed: the error is the answer
	done
	oClient.Dispose()
	return lOpen

func yesNo lValue

	if lValue
		return "yes"
	ok
	return "no"
Output
1. 192.168.1.20 is InterNetwork, 4 bytes, the first is 192
   TryParse('10.0.0.7'): yes, TryParse('999.1.1.1'): no
   '::1' is InterNetworkV6, loopback: yes
   private address 192.168.1.20 is not the loopback: yes

2. the endpoint 192.168.1.20:8080: address 192.168.1.20, port 8080

3. localhost has 2 address(es); the first is a loopback address: yes

4. ping 127.0.0.1: Success, the answer came from 127.0.0.1, fast (under 100 ms): yes

5. the computer has network interfaces: yes; one of them is the loopback: yes

6. a listener is on a port that the system chose: port is open = yes
   after Stop the same port is open = no

How it works#

Addresses and out parameters#

IPAddress.Parse("192.168.1.20") gives an object. GetAddressBytes() returns the four bytes as a Ring text (a byte[] is a text in this package), so ascii(cBytes[1]) is 192. AddressFamily is InterNetwork for IPv4 and InterNetworkV6 for IPv6, and IsLoopback tests for 127.0.0.1 and ::1.

IPAddress.TryParse(text, out address) answers yes or no without raising an error. In .NET the address comes back through an out parameter; in Ring a method with out parameters returns a list: [ success, the address ]. So aGood = oParser.TryParse("10.0.0.7") gives aGood[1] = 1 and aGood[2] = the address. The same applies to every TryParse and TryGetValue of .NET.

Endpoints#

An IPEndPoint is an address plus a port. It is made with new IPEndPoint(address, 8080).

DNS#

Dns.GetHostEntry("localhost") returns the names and addresses of a host. localhost is known without a network (usually both 127.0.0.1 and ::1). A real name such as example.com needs the internet and can take seconds or raise an error: wrap it in try / catch.

Ping#

Ping.Send("127.0.0.1") sends an ICMP echo and returns a PingReply with Status (Success, TimedOut, ...), RoundtripTime in milliseconds and Address. Pinging 127.0.0.1 tests only your own network software; ping a real host to test a connection, and give Send a timeout.

Interfaces#

NetworkInterface.GetAllNetworkInterfaces() lists the network cards (and virtual ones). NetworkInterfaceType is a text: Ethernet, Wireless80211, Loopback... Their addresses and speeds are properties too; this lesson only counts them, because the details are about your computer.

Is the port open?#

The last step starts a TcpListener on port 0 (the system chooses a free port) and checks it with portIsOpen: ConnectAsync([ :host = address, :port = port ]) starts the connection, Task.Wait(500) waits at most half a second, and a refused connection raises an error that the try turns into no. While the listener runs the answer is yes; after Stop() it is no. This is the whole idea of a port scanner — and the reason for the rules below.

Warning

Only test ports of computers that are yours or that you have permission to test. Scanning other people's computers can be a crime and is always rude. This tutorial only touches 127.0.0.1.

Note

The catch in portIsOpen also catches errors in the Ring code (a misspelled method name, for example), which then look like "port closed". While you develop, print cCatchError in the catch block.

What you learned#

Exercises#

  1. Write waitForPort(address, port, seconds) that tries every 200 ms and returns when the port opens.
  2. List the open ports of 127.0.0.1 between 8000 and 8010 after starting two listeners.
  3. Ping 127.0.0.1 five times and print the average round trip.
  4. Resolve a real host name with Dns.GetHostEntry and handle the error when there is no network.

Next#

IP networks

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.