I am using VS2008 and I am trying to complete a tutorial found at . I am however stuck halfway as I get a debug error :-
UriException is Unhandled Invalid URI: A port was expected because of there is a colon (':') present but the port could not be parsed.

This occurs after the declaration of a formatted string to a URI. Below is the code that I am using. What should I do to get around this?

using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Net;
namespace OpenNETCF.WCF.Sample
{
    class Server
    {
        static void Main(string[] args)
        {
            string hostIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].ToString();
#if CLIENT_DISCOVERY_BUILD
Uri address = new Uri(string.Format("http://localhost:8000/calculator", hostIP));
#else
            Uri address = new Uri(string.Format("", hostIP));  //THE EXCEPTION IS BEING THROWN HERE
#endif
            ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), address);
            try
            {
                // Add a service endpoint
                serviceHost.AddServiceEndpoint(typeof(ICalculator),new BasicHttpBinding(),"Calculator");
#if CLIENT_DISCOVERY_BUILD
// Enable metadata exchange
// this is needed for NetCfSvcUtil to discover us
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(smb);
#endif
                serviceHost.Open();
                Console.WriteLine(
                "CalculatorService is running at " + address.ToString());
                Console.WriteLine("Press <ENTER> to terminate");
                Console.ReadLine();
                // Close the ServiceHostBase to shutdown the service.
                serviceHost.Close();
            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("An exception occured: {0}", ce.Message);
                serviceHost.Abort();
            }
        }
    }
}

Dani AI

Generated

As correctly suggested, the exception comes from using an IPv6 literal (which contains colons) in a URI that also adds a port. The URI parser sees the extra colon(s) and expects a numeric port, so a non‑bracketed IPv6 address like http://3ffe:401d:2042::1:8000/... fails. Two simple, robust fixes: pick an IPv4 address explicitly, or build the URI so IPv6 is properly bracketed (or use UriBuilder, which handles it).

A concise, safe approach — prefer IPv4 when you need a host:port string, and use UriBuilder so you never have to manually format brackets:

using System.Linq;
using System.Net;
using System.Net.Sockets;

IPAddress ip = Dns.GetHostEntry(Dns.GetHostName()).AddressList
    .FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork)
    ?? Dns.GetHostEntry(Dns.GetHostName()).AddressList.First();

var ub = new UriBuilder("http", ip.ToString(), 8000, "calculator");
Uri address = ub.Uri;

If you must use an IPv6 address literal, wrap it in square brackets and handle any link‑local zone IDs (the % in fe80::...%3 must be escaped as %25):

string host = ip.ToString().Replace("%", "%25");
if (host.Contains(":") && !host.StartsWith("[")) host = "[" + host + "]";
Uri address = new Uri(string.Format("http://{0}:8000/calculator", host));

Also avoid relying on AddressList[0] — it’s brittle. Enumerate addresses or select the interface you intend (loopback, IPv4, global IPv6, etc.) so the address you publish is actually reachable by clients.

It looks like that machine has IPv6 enabled and you're pulling back the v6 format. You need to check IP Addresses to make sure they are IPv4.

IPv4:
IPv6: 3ffe:401d:2042::1

Example:

try
      {
        string hostIP = @"3ffe:401d:2042::1";
        IPAddress ipAddr = IPAddress.Parse(hostIP);
        Uri address = new Uri(string.Format("", hostIP));
      }
      catch (Exception ex)
      {
        Console.WriteLine("Failed: " + ex.Message);
      }

Result:

Failed: Invalid URI: A port was expected because of there is a colon (':') present but the port could not be parsed.
A first chance exception of type 'System.UriFormatException' occurred in System.dll
sk@sk:~$ host www.occaid.org
www.occaid.org has address 216.93.254.66
www.occaid.org has IPv6 address 2001:4830:100:20::6

sk@sk:~$ dig www.occaid.org any

; <<>> DiG 9.4.0 <<>> www.occaid.org any
;; global options: printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 19108
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 3, ADDITIONAL: 3

;; QUESTION SECTION:
;www.occaid.org. IN ANY

;; ANSWER SECTION:
www.occaid.org. 3574 IN AAAA 2001:4830:100:20::6
www.occaid.org. 3574 IN A

;; AUTHORITY SECTION:
occaid.org. 3574 IN NS ns1.twdx.net.
occaid.org. 3574 IN NS ns3.twdx.net.
occaid.org. 3574 IN NS ns2.twdx.net.

;; ADDITIONAL SECTION:
ns3.twdx.net. 172774 IN A
ns1.twdx.net. 172774 IN A
ns2.twdx.net. 172774 IN A

;; Query time: 4 msec
;; SERVER: ()
;; WHEN: Wed Sep 2 05:05:19 2009
;; MSG SIZE rcvd: 186

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.