This is the answer to my questions.
How to list binded/used TCP port in C#. Used modified code from jro
static void ListUsedTCPPort(ref ArrayList usedPort)
{
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();
IEnumerator myEnum = tcpConnInfoArray.GetEnumerator();
while (myEnum.MoveNext())
{
IPEndPoint TCPInfo = (IPEndPoint)myEnum.Current;
usedPort.Add(TCPInfo.Port);
}
}
Original questions.
This is how i list TCP port using C#. It is modified code i found in this forum(forgot exactly where i got it. If you are the original developer, notify me and ill put credits where due.)
//List used tcp port
static void ListUsedTCPPort(ref ArrayList usedPort)
{
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
IEnumerator myEnum = tcpConnInfoArray.GetEnumerator();
while (myEnum.MoveNext())
{
TcpConnectionInformation TCPInfo = (TcpConnectionInformation)myEnum.Current;
usedPort.Add(TCPInfo.LocalEndPoint.Port);
}
}
Problem is, the results is different from used tcp port listed in TCPview(Protocol-TCP, Local port).
By the way, i do know that this list used TCP port at the EXACT time its called.
What did i did wrong?
I get the same result:
But it does also show listeners (ipGlobalProperties.GetActiveTcpListeners()) which may or may not be closed down.
using your example (with an extra Console.WriteLine in there
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Collections;
namespace ConsoleApplication1 {
static class Program {
//List used tcp port
static void ListAvailableTCPPort(ref ArrayList usedPort) {
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
IEnumerator myEnum = tcpConnInfoArray.GetEnumerator();
while (myEnum.MoveNext()) {
TcpConnectionInformation TCPInfo = (TcpConnectionInformation)myEnum.Current;
Console.WriteLine("Port {0} {1} {2} ", TCPInfo.LocalEndPoint, TCPInfo.RemoteEndPoint, TCPInfo.State);
usedPort.Add(TCPInfo.LocalEndPoint.Port);
}
}
public static void Main(){
ArrayList usedPorts = new ArrayList();
ListAvailableTCPPort(ref usedPorts);
Console.ReadKey();
}
}
}
It's a bit of a guess but TCPView probably also shows listener tcp ports (ipGlobalProperties.GetActiveTcpListeners())
Related
I have searched everywhere but couldn't find as they are all answering to send message to all clients. What I want to achieve is multiple clients request to server to request data from another client and other client sends data to server telling it that data is for requesting client and so. I don't know how to achieve this. I'm new to this.
What I want to achieve:
I have tried with Data sending client to listen and requesting client to connect to it and transfer data. I have achieved this on local network but to make it work online it needs port forwarding and my user will be a lot of different people so port forwarding is not possible for every user. So I can rent a server which will act as a center of transfer. I programmed a test server in console which will listen to a server IP:port X and accept new clients and their data on port X and forward it to server IP:port Y but what this does is send data to all clients on port Y. I cannot send it to clients public ip address directly for obvious reasons. I understand that all the requesting clients are connected to port Y but I cannot create and assign new ports to all the clients interacting. So I want a way to determine how to request and receive the data without the need of assigning or creating new ports to different clients on same server.
What I have tried:
Server code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Test___server
{
class server
{
public static string serverIP = "192.168.0.102";
static void Main(string[] args)
{
Thread listenSendingThread = new Thread(listenSending);
listenSendingThread.IsBackground = true;
listenSendingThread.Start();
Thread listenReceivingThread = new Thread(listenReceiving);
listenReceivingThread.IsBackground = true;
listenReceivingThread.Start();
Console.ReadKey();
}
public static List<TcpClient> listSending = new List<TcpClient>();
public static List<TcpClient> listReceiving = new List<TcpClient>();
public static TcpClient clientSending = null;
private static void listenSending()
{
TcpListener listenerSending = new TcpListener(IPAddress.Parse(serverIP), 5319);
listenerSending.Start();
Console.WriteLine("Server listening to " + serverIP + ":5319");
while(true)
{
clientSending = listenerSending.AcceptTcpClient();
listSending.Add(clientSending);
Console.WriteLine("Sender connection received from " + clientSending.Client.RemoteEndPoint);
}
}
private static void send()
{
StreamWriter sw = new StreamWriter(clientSending.GetStream());
sw.WriteLine(message);
sw.Flush();
Console.WriteLine("Message sent!");
}
public static string message = string.Empty;
private static void listenReceiving()
{
TcpListener listener = new TcpListener(IPAddress.Parse(serverIP), 0045);
listener.Start();
Console.WriteLine("Server listening to " + serverIP + ":0045");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
listReceiving.Add(client);
Console.WriteLine("Receiver connection received from " + client.Client.RemoteEndPoint);
StreamReader sr = new StreamReader(client.GetStream());
message = sr.ReadLine();
send();
}
}
}
}
Requesting client code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test____admin
{
class admin
{
static void Main(string[] args)
{
Console.WriteLine("Begin");
string serverIP = "192.168.0.102";
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket.Connect(serverIP, );
Console.WriteLine("Connected");
while (true)
{
Console.WriteLine("Reading");
StreamReader sr = new StreamReader(clientSocket.GetStream());
Console.WriteLine("Message: " + sr.ReadLine());
}
}
}
}
Request satisfying client code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Test___client
{
class client
{
public static string serverIP = "192.168.0.102";
static void Main(string[] args)
{
clientConnect();
}
private static void clientConnect()
{
try
{
TcpClient client = new TcpClient(serverIP, 0045);
StreamWriter sw = new StreamWriter(client.GetStream());
sw.WriteLine("Karan!");
sw.Flush();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
You are using a very low-level API, and doing it the right way is challenging. Instead, try YARP as a reverse proxy. The requesting client should notify the reverse proxy about the desired destination client. One option is sending the destination client name in the request header. You will also need to split a single server request into multiple client requests, then merge their responses into a single one. You can achieve it by implementing Transphorms.
I'm not sure this approach applies to your situation because clients should implement server API using REST, Grpc or any other supported technology.
I am trying to receive socket communication with C # on Unity.
The following unityRecieve.cs will result in an error if Send.py is interrupted.
Send.py
import socket
import random
HOST = '127.0.0.1'
PORT = 50007
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
a = random.randrange(3)
result = str(a)
print(a)
client.sendto(result.encode('utf-8'),(HOST,PORT))
time.sleep(2.0)
unityRecieve.cs
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class unityRecieve : MonoBehaviour
{
static UdpClient udp;
void Start()
{
int LOCA_LPORT = 50007;
udp = new UdpClient(LOCA_LPORT);
udp.Client.ReceiveTimeout = 100;
}
void Update()
{
IPEndPoint remoteEP = null;
byte[] data = udp.Receive(ref remoteEP);
string text = Encoding.UTF8.GetString(data);
Debug.Log(text);
}
}
https://jump1268.hatenablog.com/entry/2018/11/25/143459
How can I make unitiRecieve.cs keep running without giving an error message when Send.py is interrupted?
Not sure if you have considered exception handling. If you did not, this might point you in the right direction.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch
i want to ignore all messages that came to serial port except unique. i add each message to hashSet and when new message arrive i check that this messages not contains in hashSet, if this message not contains i want to print him, right now my program think that each messages arrived is unique and i don't understand why my comparing code not working, maybe somebody can help me. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace mySniffer
{
class Program
{
static void Main(string[] args)
{
HashSet<String> messages = new HashSet<String>();
SerialPort comPort = new SerialPort();
comPort.BaudRate = 115200;
comPort.PortName = "COM4";
comPort.Open();
while (true)
{
string rx = comPort.ReadLine(); //reading com port
messages.Add(rx); // Add new incoming message to hashSet
if (!messages.Contains(rx))
{
Console.WriteLine(rx); // write incoming message
}
else {
Console.WriteLine(messages.Count); // check how many messages in hashSet
}
}
}
}
}
The problem was in logic of code, messages.Add(rx); should be moved in if block.
Is it possible to enumerate all open connections of the current process using .NET? (similarly to the way the netstat tool does this)
You can do this with the IPGlobalProperties class in .NET. With an instance, you can get any of the three things that netstat generally shows:
Active TCP connections, via GetActiveTcpConnections()
Active TCP listeners, via GetActiveTcpListeners()
Active UDP listeners, via GetActiveUdpListeners()
Note that there's no such thing as a "UDP connection".
Here's a simple version of netstat, using this API:
using System;
using System.Net.NetworkInformation;
namespace NetStatNet
{
class Program
{
static void Main(string[] args)
{
var props = IPGlobalProperties.GetIPGlobalProperties();
Console.WriteLine(" Proto Local Address Foreign Address State");
foreach (var conn in props.GetActiveTcpConnections())
Console.WriteLine(" TCP {0,-23}{1,-23}{2}",
conn.LocalEndPoint, conn.RemoteEndPoint, conn.State);
foreach (var listener in props.GetActiveTcpListeners())
Console.WriteLine(" TCP {0,-23}{1,-23}{2}", listener, "", "Listening");
foreach (var listener in props.GetActiveUdpListeners())
Console.WriteLine(" UDP {0,-23}{1,-23}{2}", listener, "", "Listening");
Console.Read();
}
}
}
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
you have to convert this array to IEnum
i'm trying to make an application for my laptop which in case i forgot to log off, i can use my smarthphone to log off by using a specific app for that. So i was thinking usually if you have a router... you have a problem cause you don't have the external ip which you can use, and the port. For that i used this function to get the external ip.
public string adresaIP()
{
UTF8Encoding utf8 = new UTF8Encoding();
WebClient clientWeb = new WebClient();
String adresaIP = utf8.GetString(clientWeb.DownloadData("http://bot.whatismyipaddress.com"));
return adresaIP;
}
But when i try to use te IpEndPoint it dosen't work it give's me an exception Error and i don't know were i did wrong.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace bluetooth_LogOff
{
public partial class Form1 : Form
{
static byte[] buffer { get; set; }
static Socket soket;
public Form1()
{
InitializeComponent();
try
{
string ip = adresaIP();
soket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//soket.Bind(new IPEndPoint(IPAddress.Parse(ip),1234)); <<-- in this way dosen't work
soket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"),1234)); // <<- in this way it works....
soket.Listen(100);
Socket accept = soket.Accept();
buffer = new byte[accept.SendBufferSize];
int bytesRead = accept.Receive(buffer);
byte[] format = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
{
format[i] = buffer[i];
}
string primescMesaj = Encoding.ASCII.GetString(format);
MessageBox.Show(primescMesaj);
soket.Close();
accept.Close();
}
catch (Exception messaj)
{
MessageBox.Show(messaj.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = adresaIP();
}
public string adresaIP()
{
UTF8Encoding utf8 = new UTF8Encoding();
WebClient clientWeb = new WebClient();
String adresaIP = `utf8.GetString(clientWeb.DownloadData("http://bot.whatismyipaddress.com"));`
return adresaIP;
}
}
}
But the funny thing is if i put the addres like "127.0.0.1" It works, but if i put the string addres it dosen't
You cannot bind to the external address that address belongs to the router.
You should bind to address 0.0.0.0 (all addresses) on your laptop and configure your router to forward the laptop port (or use UPnP).
The reason you cannot access your laptop directly is because your router, like most routers is a NAT (network address translation) router. It allows several computers to hide behind a single IP address. So the router will have a public IP address and your laptop and other devices behind the router will have a private IP address (such as those in the range 192.168.x.x)
Most NAT routers can be configured with static port forwarding; i.e. the port in a specific private address is reflected in the same or a different port in the public IP.
This allows access to internal devices from the public internet. UPnP is a protocol that does the same thing, but does not require manual configuration on the router. UPnP is usually how P2P applications and some multi-player games gain public accessible ports without human intervention. It is also why UPnP may be considered a security hazard since the computer owner may not be aware of such forwarding.