Can't send multicast over non-default NIC - c#

On a Windows 7 VM, I am trying to send UDP packets to a multicast address using the second (non-default) of two network interfaces. I can achieve this with mcast using the /INTF option (which doesn't allow specifying the port), but my C# code doesn't work:
void run(string ipaddrstr, int port, string nicaddrstr)
{
int index = -1;
// Create a socket for the UDP broadcast
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress ipaddr = IPAddress.Parse(ipaddrstr);
IPAddress nicAddr = IPAddress.Parse(nicaddrstr);
int i = 0;
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) {
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) {
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) {
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
if (ip.Address.Equals(nicAddr)) {
index = i;
break;
}
}
}
if (index != -1) {
break;
}
i++;
}
if (index == -1) {
Console.Error.WriteLine("Couldn't find NIC with IP address '" + nicaddrstr + "'");
return;
}
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ipaddr, nicAddr));
int multicastInterfaceIndex = (int)IPAddress.HostToNetworkOrder(index);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, multicastInterfaceIndex);
}
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 1);
IPEndPoint endpoint = new IPEndPoint(ipaddr, port);
socket.Connect(endpoint);
// At this point, data can be send to the socket
}
When I specify nicaddrstr as the default network interface IP address, data flows as expected on that interface. However, if I specify nicaddrstr as the second (non-default) network interface IP address, no data flows (as verified by Wireshark), even though no error is thrown in any function call. Can someone tell me what mcast is doing that allows the non-default NIC to accept the UDP data?
I've tried various combinations of route settings in the route table, but the contents don't seem to affect the behavior of this code.

Related

How to find the proper IPAddress to use to open a TCP/IP server port when there is many network adapters

I can't find code to find the proper IP address to use to open a TCP/IP server port on my machine.
The problem occurs because I have many network adapters. I have some Virtual Machine(s) (for example: HyperV / VirtualBox / VmWare) which create virtual network adapter and each one has its one IPAddress. So how to avoid those IPAddress (proper network card) and find the only one used to access the internet for real?
When I try to find the proper IP Address, I get the virtual network adapter card Ip Adress instead of the physical one using this code:
IPAddress properIpAddress = null;
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface networkInterface in interfaces)
{
var ipProps = networkInterface.GetIPProperties();
foreach (var ip in ipProps.UnicastAddresses)
{
if ((networkInterface.OperationalStatus == OperationalStatus.Up) && (ip.Address.AddressFamily == AddressFamily.InterNetwork))
{
if (ip.Address.ToString() == "127.0.0.1")
{
continue;
}
properIpAddress = ip.Address;
// Console.Out.WriteLine(ip.Address.ToString() + "|" + networkInterface.Description.ToString());
Debug.WriteLine(ip.Address.ToString() + "|" + networkInterface.Description.ToString());
break;
}
}
if (properIpAddress != null)
{
break;
}
}
The real solution is to not search for an adapter in the first place.
Just use IPAddress.Any to listen on all interfaces at the given port.
using(TcpListener tcpListener = new TcpListener(IPAddress.Any, somePortNumber))
{
// some code
}
I've been using the following code for this. It gets you the IP that an outgoing connection would use:
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
return endPoint.Address;
}
Note however, that it does open a socket - so maybe one should cache the result.
I'm now using this code which works fine for me but I'm not sure it is bullet proof.
I share my code as reference because I haven't found something that worked for me, other that this:
IPAddress properIpAddress = null;
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface networkInterface in interfaces)
{
var ipProps = networkInterface.GetIPProperties();
foreach (var ip in ipProps.UnicastAddresses)
{
if ((networkInterface.OperationalStatus == OperationalStatus.Up)
&& (ip.Address.AddressFamily == AddressFamily.InterNetwork)
&& (ipProps.IsDnsEnabled || ipProps.IsDynamicDnsEnabled))
{
if (ip.Address.ToString() == "127.0.0.1")
{
continue;
}
properIpAddress = ip.Address;
// Console.Out.WriteLine(ip.Address.ToString() + "|" + networkInterface.Description.ToString());
Debug.WriteLine(ip.Address.ToString() + "|" + networkInterface.Description.ToString());
break;
}
}
if (properIpAddress != null)
{
break;
}
}

Specify what interface use to send multicast IGMP JOIN (c# socket)

I would like to choose which network interface to use to send a join request.
This is the code I tried but I don't think it's right:
static int GetNicIndexByIP(String ipAddress)
{
int adapterIndex = -1;
IPAddressInformation[] adapterIPs;
foreach (NetworkInterface adapter in nics)
{
adapterIPs = adapter.GetIPProperties().UnicastAddresses.ToArray();
adapterIndex = (int)IPAddress.HostToNetworkOrder(adapter.GetIPProperties().GetIPv4Properties().Index);
foreach (IPAddressInformation ip in adapterIPs)
{
if (ip.Address.ToString() == ipAddress)
return adapterIndex;
}
}
return -1;
}
string nicAddress = "192.168.1.100";
string multicastAddress = "229.1.0.1";
int nicIndex = GetNicIndexByIP(nicAddress);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// first try: ignored (sent from another interface)
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, nicIndex);
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(multicastAddress)));
// second try: error argument "229.1.0.1" out of range
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(multicastAddress), nicIndex));
if anyone is interested, I found the answer myself:
MulticastOption mcastOption = new MulticastOption(IPAddress.Parse(multicastAddress), IPAddress.Parse(nicAddress));
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcastOption);

Connect Multiple TCP/IP devices by Creating N Number of Sockets to Connect to N number of IP Addresses

I would like to connect to multiple TCP/IP devices simultaneously to read or send data by creating N number of sockets to connect to N number of IP addresses. I had written the code as below but it will only create one socket to connect to the first IP address instead of creating 3 sockets to connect to 3 IP addresses. Please help. Thanks.
Similar post : How to connect multiple IP addresses with same port number using TCP/IP client?
Socket[] sockets = new Socket[3];
IPAddress[] ipaddress = new IPAddress[3];
string tempIP = "192.168.1.13";
private void StartClient()
{
try
{
for (int i = 0; i < 3; i++)
{
sockets[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
for (int j = 0; j < 3; j++)
{
ipaddress[j] = IPAddress.Parse(tempIP + (j + 3));
remoteEP = new IPEndPoint(ipaddress[j], port);
MessageBox.Show(remoteEP.ToString());
var result = sockets[i].BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), sockets[i]);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
MessageBox.Show(success.ToString());
if (!success && ButtonStartScan.Text == "Connected")
{
Thread.Sleep(10000);
PortDisconnect();
Thread.Sleep(10000);
PortConnect();
throw new Exception("Failed to connect.");
}
connectDone.WaitOne(1);
if (ButtonStartScan.Text == "Disconnected")
{
PortDisconnect();
}
else
{
stopwatch1.Start();
receiveDone.Reset();
Receive(sockets[i]);
bool poll_check = true;
do
{
if (stopwatch1.ElapsedMilliseconds > 10000)
{
stopwatch1.Restart();
string X5 = "X5";
Send_stop(sockets[i], X5);
sendDone.WaitOne(1000);
for (int row = 0; row < DroneList.Rows.Count; row++)
{
TimeSpan timeDiff = DateTime.Now - Convert.ToDateTime(DroneList.Rows[row].Cells["TimeDetected"].Value);
int time = Convert.ToInt32(timeDiff.TotalSeconds);
if (time > dronecounter)
{
DroneList.Rows[row].Cells["Inject"].Style.BackColor = Color.DarkGray;
if (!DroneList.Rows[row].Cells["DroneType"].Value.ToString().Contains("Wifi"))
{
DroneStatus.ImageLayout = DataGridViewImageCellLayout.Zoom;
Image img1 = Image.FromFile(#"D:\Image\no_alert.PNG");
DroneList.Rows[row].Cells["DroneStatus"].Value = img1;
}
SignalStrength.ImageLayout = DataGridViewImageCellLayout.Zoom;
Image img2 = Image.FromFile(#"D:\Image\no_bar.PNG");
DroneList.Rows[row].Cells["SignalStrength"].Value = img2;
if (DroneList.Rows[row].Cells["Inject"].Value.ToString() == "Stop Distract")
{
if (DroneList.Rows[row].Cells["DroneType"].Value.ToString() == "DJI Phantom 3 STD")
{
DroneList.Rows[row].Cells["Inject"].Style.ForeColor = Color.DodgerBlue;
DroneList.Rows[row].Cells["Inject"].Value = "Inject";
string StopString = "S3";
Send_stop(sockets[i], StopString);
sendDone.WaitOne(1000);
}
else
{
DroneList.Rows[row].Cells["Inject"].Style.ForeColor = Color.DodgerBlue;
DroneList.Rows[row].Cells["Inject"].Value = "Distract";
string StopString = "SD";
Send_stop(sockets[i], StopString);
sendDone.WaitOne(1000);
}
}
}
}
if (!sockets[i].Connected)
{
for (int row = 0; row < DroneList.Rows.Count; row++)
{
if (DroneList.Rows[row].DefaultCellStyle.BackColor == Color.DarkGray)
{
}
else
{
if (DroneList.Rows[row].Cells["Inject"].Value.ToString() == "Stop Inject")
{
if (DroneList.Rows[row].Cells["DroneType"].Value.ToString() == "DJI Phantom 3 STD")
{
DroneList.Rows[row].Cells["Inject"].Style.ForeColor = Color.DodgerBlue;
DroneList.Rows[row].Cells["Inject"].Value = "Distract";
string StopString = "S3";
Send_stop(sockets[i], StopString);
sendDone.WaitOne(1000);
}
else
{
DroneList.Rows[row].Cells["Inject"].Style.ForeColor = Color.DodgerBlue;
DroneList.Rows[row].Cells["Inject"].Value = "Distract";
string StopString = "SD";
Send_stop(sockets[i], StopString);
sendDone.WaitOne(1000);
}
}
DroneList.Rows[row].DefaultCellStyle.BackColor = Color.DarkGray;
DroneList.Rows[row].Cells["Inject"].Style.BackColor = Color.DarkGray;
DroneList.Rows[row].Cells["Whitelist"].Style.BackColor = Color.DarkGray;
if (!DroneList.Rows[row].Cells["DroneType"].Value.ToString().Contains("Wifi"))
{
DroneStatus.ImageLayout = DataGridViewImageCellLayout.Zoom;
Image img1 = Image.FromFile(#"D:\Image\no_alert.PNG");
DroneList.Rows[row].Cells["DroneStatus"].Value = img1;
}
SignalStrength.ImageLayout = DataGridViewImageCellLayout.Zoom;
Image img2 = Image.FromFile(#"D:\Image\no_bar.PNG");
DroneList.Rows[row].Cells["SignalStrength"].Value = img2;
}
}
PortDisconnect();
Thread.Sleep(10000);
PortConnect();
Thread.Sleep(10000);
}
}
}
while (poll_check);
receiveDone.WaitOne();
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Just use a individual TCP socket for each connection/device. It doesn't matter that all devices have the same port, as this is only the port used by the remote device. Your pc will randomly choose a port for the outgoing connection, and you can't (and don't want to) do anything about it.
For example, this is what the communication will look like. The outgoing port really doesn't matter at all:
Your PC:4568 --> xxx.xx.xx.100:8000
Your PC:7568 --> xxx.xx.xx.101:8000
xxx.xx.xx.100:8000 --> Your PC:4568
xxx.xx.xx.101:8000 --> Your PC:7568
Edit:
If you have a small, fixed number of devices, you can just use multiple sockets like this:
Socket client1;
Socket client2;
Socket client3;
client1 = new Socket(IPAddress.Parse("xxx.xxx.xxx.100").AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
client2 = new Socket(IPAddress.Parse("xxx.xxx.xxx.100").AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
client3 = new Socket(IPAddress.Parse("xxx.xxx.xxx.100").AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
remoteEP1 = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.100"), port);
remoteEP1 = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.101"), port);
remoteEP1 = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.102"), port);
If you have a bigger number of devices, or the ip addresses change dynamically, it would make sense to create the sockets in a for-loop and write them to an array.
This is a Networking problem first and barely even a Programming one. The network classes do not care if the target is on the same computer, the same switch or the Voyager Probes.
Socket and IP adress are a integral pair. You can not seperate them from each other.
Knowing only the sockete would be like only knowing the House Number, but not the street. And the IP adress would be only knowing the street, but not which of the several thousand housenumbers.
Communication goes from one pair of IP/Socket to another pair of IP/Socket. In many cases the socket number can be implied. HTTP request usally target Port 80 on the target IP adress.
If you are mostly doing receiving work with limited communication, you can share a port for multiple clients. Port 80 does so. But if the communicaiton is more complex, it is customary to only use the public port to innitate talking, then to all the heavy lifting on a port specific for this process that you jsut dynamically aquire.

Get IPv4 addresses from Dns.GetHostEntry()

I've got some code here that works great on IPv4 machines, but on our build server (an IPv6) it fails. In a nutshell:
IPHostEntry ipHostEntry = Dns.GetHostEntry(string.Empty);
The documentation for GetHostEntry says that passing in string.Empty will get you the IPv4 address of the localhost. This is what I want. The problem is that it's returning the string "::1:" on our IPv6 machine, which I believe is the IPv6 address.
Pinging the machine from any other IPv4 machine gives a good IPv4 address... and doing a "ping -4 machinename" from itself gives the correct IPv4 address.... but pinging it regularly from itself gives "::1:".
How can I get the IPv4 for this machine, from itself?
Have you looked at all the addresses in the return, discard the ones of family InterNetworkV6 and retain only the IPv4 ones?
To find all local IPv4 addresses:
IPAddress[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
a => a.AddressFamily == AddressFamily.InterNetwork);
or use Array.Find or Array.FindLast if you just want one.
IPHostEntry ipHostInfo = Dns.GetHostEntry(serverName);
IPAddress ipAddress = ipHostInfo.AddressList
.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
public Form1()
{
InitializeComponent();
string myHost = System.Net.Dns.GetHostName();
string myIP = null;
for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
{
if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
{
myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
}
}
}
Declare myIP and myHost in public Variable
and use in any function of the form.
public static string GetIPAddress(string hostname)
{
IPHostEntry host;
host = Dns.GetHostEntry(hostname);
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
//System.Diagnostics.Debug.WriteLine("LocalIPadress: " + ip);
return ip.ToString();
}
}
return string.Empty;
}
To find all valid address list this is the code I have used
public static IEnumerable<string> GetAddresses()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}
You can get all IPv4 address from the DNS using this code:
IPs[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
address => address.AddressFamily == AddressFamily.InterNetwork);
IPv6
lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0).ToString()
IPv4
lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(1).ToString()

Find the next TCP port in .NET

I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port.
I know that TcpClient will assign a new client side port when I open a connection to a given server.
Is there a simple way to find the next open TCP port in .NET?
I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
Here is what I was looking for:
static int FreeTcpPort()
{
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
Use a port number of 0. The TCP stack will allocate the next free one.
It's a solution comparable to the accepted answer of TheSeeker. Though I think it's more readable:
using System;
using System.Net;
using System.Net.Sockets;
private static readonly IPEndPoint DefaultLoopbackEndpoint = new IPEndPoint(IPAddress.Loopback, port: 0);
public static int GetAvailablePort()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(DefaultLoopbackEndpoint);
return ((IPEndPoint)socket.LocalEndPoint).Port;
}
}
I found the following code from Selenium.WebDriver DLL
Namespace: OpenQA.Selenium.Internal
Class: PortUtility
public static int FindFreePort()
{
int port = 0;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 0);
socket.Bind(localEP);
localEP = (IPEndPoint)socket.LocalEndPoint;
port = localEP.Port;
}
finally
{
socket.Close();
}
return port;
}
If you just want to give a starting port, and let it return to you the next TCP port available, use code like this:
public static int GetAvailablePort(int startingPort)
{
var portArray = new List<int>();
var properties = IPGlobalProperties.GetIPGlobalProperties();
// Ignore active connections
var connections = properties.GetActiveTcpConnections();
portArray.AddRange(from n in connections
where n.LocalEndPoint.Port >= startingPort
select n.LocalEndPoint.Port);
// Ignore active tcp listners
var endPoints = properties.GetActiveTcpListeners();
portArray.AddRange(from n in endPoints
where n.Port >= startingPort
select n.Port);
// Ignore active UDP listeners
endPoints = properties.GetActiveUdpListeners();
portArray.AddRange(from n in endPoints
where n.Port >= startingPort
select n.Port);
portArray.Sort();
for (var i = startingPort; i < UInt16.MaxValue; i++)
if (!portArray.Contains(i))
return i;
return 0;
}
First open the port, then give the correct port number to the other process.
Otherwise it is still possible that some other process opens the port first and you still have a different one.
Here's a more abbreviated way to implement this if you want to find the next available TCP port within a given range:
private int GetNextUnusedPort(int min, int max)
{
if (max < min)
throw new ArgumentException("Max cannot be less than min.");
var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
var usedPorts =
ipProperties.GetActiveTcpConnections()
.Where(connection => connection.State != TcpState.Closed)
.Select(connection => connection.LocalEndPoint)
.Concat(ipProperties.GetActiveTcpListeners())
.Concat(ipProperties.GetActiveUdpListeners())
.Select(endpoint => endpoint.Port)
.ToArray();
var firstUnused =
Enumerable.Range(min, max - min)
.Where(port => !usedPorts.Contains(port))
.Select(port => new int?(port))
.FirstOrDefault();
if (!firstUnused.HasValue)
throw new Exception($"All local TCP ports between {min} and {max} are currently in use.");
return firstUnused.Value;
}
If you want to get a free port in a specific range in order to use it as local port / end point:
private int GetFreePortInRange(int PortStartIndex, int PortEndIndex)
{
DevUtils.LogDebugMessage(string.Format("GetFreePortInRange, PortStartIndex: {0} PortEndIndex: {1}", PortStartIndex, PortEndIndex));
try
{
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpEndPoints = ipGlobalProperties.GetActiveTcpListeners();
List<int> usedServerTCpPorts = tcpEndPoints.Select(p => p.Port).ToList<int>();
IPEndPoint[] udpEndPoints = ipGlobalProperties.GetActiveUdpListeners();
List<int> usedServerUdpPorts = udpEndPoints.Select(p => p.Port).ToList<int>();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
List<int> usedPorts = tcpConnInfoArray.Where(p=> p.State != TcpState.Closed).Select(p => p.LocalEndPoint.Port).ToList<int>();
usedPorts.AddRange(usedServerTCpPorts.ToArray());
usedPorts.AddRange(usedServerUdpPorts.ToArray());
int unusedPort = 0;
for (int port = PortStartIndex; port < PortEndIndex; port++)
{
if (!usedPorts.Contains(port))
{
unusedPort = port;
break;
}
}
DevUtils.LogDebugMessage(string.Format("Local unused Port:{0}", unusedPort.ToString()));
if (unusedPort == 0)
{
DevUtils.LogErrorMessage("Out of ports");
throw new ApplicationException("GetFreePortInRange, Out of ports");
}
return unusedPort;
}
catch (Exception ex)
{
string errorMessage = ex.Message;
DevUtils.LogErrorMessage(errorMessage);
throw;
}
}
private int GetLocalFreePort()
{
int hemoStartLocalPort = int.Parse(DBConfig.GetField("Site.Config.hemoStartLocalPort"));
int hemoEndLocalPort = int.Parse(DBConfig.GetField("Site.Config.hemoEndLocalPort"));
int localPort = GetFreePortInRange(hemoStartLocalPort, hemoEndLocalPort);
DevUtils.LogDebugMessage(string.Format("Local Free Port:{0}", localPort.ToString()));
return localPort;
}
public void Connect(string host, int port)
{
try
{
// Create socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
var localPort = GetLocalFreePort();
// Create an endpoint for the specified IP on any port
IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort);
// Bind the socket to the endpoint
socket.Bind(bindEndPoint);
// Connect to host
socket.Connect(IPAddress.Parse(host), port);
socket.Dispose();
}
catch (SocketException ex)
{
// Get the error message
string errorMessage = ex.Message;
DevUtils.LogErrorMessage(errorMessage);
}
}
public void Connect2(string host, int port)
{
try
{
// Create socket
var localPort = GetLocalFreePort();
// Create an endpoint for the specified IP on any port
IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort);
var client = new TcpClient(bindEndPoint);
//client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //will release port when done
// Connect to the host
client.Connect(IPAddress.Parse(host), port);
client.Close();
}
catch (SocketException ex)
{
// Get the error message
string errorMessage = ex.Message;
DevUtils.LogErrorMessage(errorMessage);
}
}

Categories