Random Port Assignment in Azure

One thing to remember when developing a service on Azure is that the port defined in ServiceDefinition.csdef by the following

<InputEndpoint name="MyService" protocol="tcp" port="200" />

is not the same as the port your service should map to.

In other words when creating a socket within your service, Azure assigns a “random” port to your service, so it may have assigned your service the port 1234. So had you created your socket listening to port 200 (as defined in the config file) you will find your service doesn’t receive any traffic.

This is because the port defined in the configuration file is really aimed at the load balancer. It will open the defined port for traffic then route it to the “random” port assigned by Azure to your service. So to create a socket to listen for traffic we need to use the Service Runtime API in Azure to find the port assigned to the service.

RoleEnvironment re = RoleEnvironment.CurrentRoleInstance.InstanceEndPoints["MyService"];
IPEndPoint ep = re.IPEndpoint;

Socket socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ep);
socket.Listen(1000);