blob: 1ad33c108d8f9b53c99c4d7d0b24a079b42611ae [file] [log] [blame]
// <copyright file="PortUtilities.cs" company="WebDriver Committers">
// Copyright 2007-2012 WebDriver committers
// Copyright 2007-2012 Google Inc.
// Portions copyright 2012 Software Freedom Conservancy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace OpenQA.Selenium.Internal
{
/// <summary>
/// Encapsulates methods for working with ports.
/// </summary>
internal static class PortUtilities
{
/// <summary>
/// Finds a random, free port to be listened on.
/// </summary>
/// <returns>A random, free port to be listened on.</returns>
public static int FindFreePort()
{
// Locate a free port on the local machine by binding a socket to
// an IPEndPoint using IPAddress.Any and port 0. The socket will
// select a free port.
int listeningPort = 0;
Socket portSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IPEndPoint socketEndPoint = new IPEndPoint(IPAddress.Any, 0);
portSocket.Bind(socketEndPoint);
socketEndPoint = (IPEndPoint)portSocket.LocalEndPoint;
listeningPort = socketEndPoint.Port;
}
finally
{
portSocket.Close();
}
return listeningPort;
}
}
}