Send broadcast with unknown port - c#

Is it possible, to send a broadcast for searching a server application, if i don't know the port on which the server is running? Or do i have to check every port?
To send a simple broadcast, i found the following code at the internet:
Server
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Console.Write("Running server..." + Environment.NewLine);
server.Bind(new IPEndPoint(IPAddress.Any, 48000));
while (true)
{
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
byte[] buffer = new byte[1000];
server.ReceiveFrom(buffer, ref tempRemoteEP);
Console.Write("Server got '" + buffer[0] + "' from " + tempRemoteEP.ToString() + Environment.NewLine);
Console.Write("Sending '2' to " + tempRemoteEP.ToString() +
Environment.NewLine);
server.SendTo(new byte[] { 2 },
tempRemoteEP);
}
Client
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint AllEndPoint = new IPEndPoint(IPAddress.Broadcast, 48000);
//Allow sending broadcast messages
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);
//Send message to everyone
client.SendTo(new byte[] { 1 }, AllEndPoint);
Console.Write("Client send '1' to " + AllEndPoint.ToString() +
Environment.NewLine);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
byte[] buffer = new byte[1000];
string serverIp;
try
{
//Recieve from server. Don't wait more than 3000 milliseconds.
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 3000);
client.ReceiveFrom(buffer, ref tempRemoteEP);
Console.Write("Client got '" + buffer[0] + "' from " +
tempRemoteEP.ToString() + Environment.NewLine);
//Get server IP (ugly)
serverIp = tempRemoteEP.ToString().Split(":".ToCharArray(), 2)[0];
}
catch
{
//Timout. No server answered.
serverIp = "?";
}
Console.Write("ServerIp: " + serverIp + Environment.NewLine);
Console.ReadLine();
But I don't know, wehter my server use port 48000.

To send a broadcast:
var port = 123;
var udp = new UdpClient();
var data = new byte[] { 1, 2, 3 };
udp.Send(data, data.Length, new IPEndPoint(IPAddress.Any, port));
If you don't know the port, you have to try all ports, which I do not recommend, since you're spamming the network.
What are you trying to do?

Related

How to have a C# TCP Chat Server listen for connections from multiple clients?

So this is code for my TCP based chat server written in c#. It works no problem for connecting two computers via ipv4 for chat, but I am wanting the server program to listen for and accept, then send a "sucessfully joined" message to the computers that joined.
I am wondering is there a way to change this code to do this?
Server code:
IPAddress ipAd = IPAddress.Parse(IPV4.Text); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The message " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
/* clean up */
s.Close();
myList.Stop();
Client code:
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(RecieveIPAdd.Text, 8001); // use the ipaddress as in the server program
MessageBox.Show("Connected");
Stream stm = tcpclnt.GetStream();
MessageBox.Show("Listening for attack information......");
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string atk = Encoding.UTF8.GetString(bb.AsSpan(0, k));
Thank you.
// Code after help
private void Connectnattk_DoWork(object sender, DoWorkEventArgs e)
{
{
{
try
{
IPAddress ipAd = IPAddress.Parse(IPV4.Text); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The command " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
void ServerStart()
{
TcpListener listener = new TcpListener(IPAddress.Any, 8001);
listener.Start();
Console.WriteLine("Listening on port: 8001");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
}
}
void HandleConnection(TcpClient client)
{
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
Console.WriteLine("Number of connected buddies: " + connectedbuddies++);
client.Close();
}
/* clean up */
s.Close();
myList.Stop();
}
Accepting a client socket in your code is synchronous, so you can only accept one client, process it then loop around to accept and process another.
You can use threads to add parallelism to your code. You create a method for handling client sockets and create a new thread for the client socket. This will allow you to continue looping to accept new incoming client socket connections whilst processing existing client socket connections.
static void ServerStart()
{
TcpListener listener = new TcpListener(IPAddress.Any, 4480);
listener.Start();
Console.WriteLine("Listening on port: 4480");
while (true)
{
// Accept the client connection before creating the thread.
TcpClient client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
}
}
static void HandleConnection(TcpClient client)
{
// Insert your code here. (Do not accept socket again here)
client.Close();
}
I create a new thread to run the HandleConnection method for each TcpClient using ThreadPool. You can create threads without ThreadPool however if threads are short-lived for performance reasons, you will want to use ThreadPool to create them.

TCP/IP CLIENT RECEIVE MULTIPLE MESSAGE

I need a help about my server. I have a program that sends a message over a socket with a TCP/IP connection and gets acknowledgment. My current problem is: I'm sending data to the machine I'm using for it to print. The machine confirms that it has received the data each time. But now it has to give feedback that it has printed the data after confirming that it has received the data. In the program I wrote, I cannot receive 2 messages in a row from the machine. What do I need to do to listen to multiple messages over Socket?
The code I use is below. Thanks for helps...
private void clientBaglanti(string ipAdres, int portNumarasi)
{
try
{
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = IPAddress.Parse(ipAdres); //ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, portNumarasi);
soket = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
catch (Exception rt)
{
MessageBox.Show(rt.Message);
}
string sonMesaj;
sonMesaj = gonderilenText.ToCharArray().Aggregate("", (sonuc, c) => sonuc += ((!string.IsNullOrEmpty(sonuc) && (sonuc.Length + 1) % 3 == 0) ? " " : "") + c.ToString());
byte[] gonderilenVeri = sonMesaj.Split().Select(s => Convert.ToByte(s, 16)).ToArray();
byte b = checksumHesap(gonderilenVeri);
string txtChecksum = b.ToString("X2");
string toplamMesaj = sonMesaj + (" ") + txtChecksum;
byte[] gonderilenSonVeri = toplamMesaj.Split().Select(s => Convert.ToByte(s, 16)).ToArray();
int byteGonderilen = soket.Send(gonderilenSonVeri);
string stringGidenVeri = BitConverter.ToString(gonderilenSonVeri);
lstVtMakineHaberlesme.Items.Add("Gönderilen: " + stringGidenVeri);
byte[] cevap = new byte[1024];
int ht = soket.Receive(cevap);
string stringGelenVeri = BitConverter.ToString(cevap, 0, ht);
lstVtMakineHaberlesme.Items.Add("Gelen: " + stringGelenVeri);

c# test bandwidth between server and client applications

I am new to programming. For my first application I decided to create two console applications - server and client application. I want to test data transaction bandwith between client and server app(by the way I am using sockets). The problem I have is that I need to test connection speed for, lets say 10 seconds and after those 10 seconds I need to get received data amount (which I have received in this time period) and calculate speed...How can I do that?
Client app
namespace Example_01_Sockets_Client
{
class MainClass
{
public static void Main(string[] args)
{
try
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var ownAddress = IPAddress.Parse("127.0.0.1");
var ownEndpoint = new IPEndPoint(ownAddress, 4321);
socket.Bind(ownEndpoint);
Console.WriteLine();
Console.WriteLine("Trying to connect to server...");
var serverAddress = IPAddress.Parse("127.0.0.1");
socket.Connect(serverAddress, 2222);
Console.WriteLine("Connected to server");
var buffer = new byte[1024 * 150000];
socket.ReceiveTimeout = 100;
int receivedBytesLen = socket.Receive(buffer);
Console.WriteLine("Download speed: " + ((receivedBytesLen) / 100 + "kb/s ") );
Console.WriteLine("Press any key to exit");
Console.ReadKey();
socket.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
Server App
class MainClass
{
public static void Main(string[] args)
{
bool exit = false;
while (!exit)
{
var listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndpoint = new IPEndPoint(ipAddress, 2222);
listeningSocket.Bind(localEndpoint);
listeningSocket.Listen(1);
Console.WriteLine();
Console.WriteLine("Waiting for client...");
Socket connectedSocket = listeningSocket.Accept();
listeningSocket.Close();
string clientAddress = connectedSocket.RemoteEndPoint.ToString();
Console.WriteLine("Client connected (" + clientAddress + ")");
string fileName = "downTest.txt";
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
byte[] fileData = File.ReadAllBytes(fileName);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
connectedSocket.Send(fileData);
//int bytesReceived = connectedSocket.Receive();
Console.WriteLine("Client connected (" + clientAddress + ")");
connectedSocket.Close();
}
}
}
Thanks for any help!!!
Why not use a set amount of data (eg. 4,096kb). Use the Stopwatch class to start a timer right before you start downloading data on the client, and then stop the timer immediately after it finishes sending. You can then use the elapsed time property to determine how long it took to send that fixed amount of data.
Stopwatch timer = new Stopwatch();
timer.Start();
// Download data here
timer.Stop();
int elapsedTime = timer.Elapsed.TotalSeconds;

C# UDP Server talk with Client

I've tried multiple methods of doing this, and non seem to work out. But there must be a way.
What I'm trying to do (in C#) is create a server. I want the server to listen on a IP and port, and when it connects to a client, I want it to read what the client says, and send a reply. For the client, I want to connect to a server and send data, and receive the reply from the server.
How can I go about doing this?
I've used Microsoft examples and examples found on MSDN. They have Client > data > Server but it doesn't ever seem to include the server reply.
I know this can be done, obviously, because we have multiplayer games.
Thanks for the help.
EDIT - Code snippets
SERVER
static void Main(string[] args)
{
int recv;
byte[] data = new byte[1024];
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 904);
Socket newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
newSocket.Bind(endPoint);
Console.WriteLine("Listening for connections...");
//LISTEN FOR CLIENT
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 904);
EndPoint tmpRemote = (EndPoint)sender;
//READ MESSAGE FROM CLIENT
recv = newSocket.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine("Messaged received from: " + tmpRemote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
string welcome = "Welcome to server!";
data = Encoding.ASCII.GetBytes(welcome);
//SEND WELCOME REPLY TO CLIENT
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.Bind(tmpRemote);
sock.SendTo(data, tmpRemote);
Console.WriteLine("Reply sent to client");
while (true)
{
if(!newSocket.Connected)
{
Console.WriteLine("Client disconnected.");
break;
}
data = new byte[1024];
recv = newSocket.ReceiveFrom(data, ref tmpRemote);
if (recv == 0)
break;
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
}
newSocket.Close();
Console.WriteLine("Server disconnected.");
Console.ReadLine();
}
}
CLIENT
static void Main(string[] args)
{
Console.WriteLine("Message [127.0.0.1:904]: ");
string msg = Console.ReadLine();
byte[] packetData = ASCIIEncoding.ASCII.GetBytes(msg);
string IP = "127.0.0.1";
int port = 904;
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.SendTo(packetData, ep);
Console.WriteLine("Data sent!");
int recv;
byte[] data = new byte[1024];
EndPoint tmpRemote = (EndPoint)ep;
while(true)
{
//READ MESSAGE FROM SERVER
recv = client.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine("Messaged received from: " + tmpRemote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
}
client.Close();
Console.WriteLine("Client disconnected.");
Console.ReadLine();
}
I can't get the server to talk back to the client and have the client read/display the server's reply.
change this sentence
sock.SendTo(data, tmpRemote);
to
newSocket.SendTo(data, tmpRemote);
and remove these sentences, you have bind local EndPoint twice.
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.Bind(tmpRemote);
In Net, you can use UdpClient instead of Socket.
If you want a demo, look at this demo.

How to join source specific multicast group in C# (IGMPv3)

We have a C# application that can join and receives data from a multicast group. This works well. We now want to support IGMPv3 and be able to specify the IP of the source when joining a multicast group. From the MSDN documentation, I don't see how to do this. I have found the following link that seems to answer my question.
http://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/e8063f6d-22f5-445e-a00c-bf46b46c1561
And here is how I implemented this:
byte[] membershipAddresses = new byte[12]; // 3 IPs * 4 bytes (IPv4)
Buffer.BlockCopy(multicastIp.GetAddressBytes(), 0, membershipAddresses, 0, 4);
Buffer.BlockCopy(sourceIp.GetAddressBytes(), 0, membershipAddresses, 4, 4);
Buffer.BlockCopy(localIp.GetAddressBytes(), 0, membershipAddresses, 8, 4);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, membershipAddresses);
But I get a SocketException when calling SetSocketOption() with this error: The requested address is not valid in its context.
Can someone points me what I am doing wrong here? Thanks!
The link states SocketOptionName.AddSourceMembership, you are using AddMembership.
For anyone struggling with source multicast
static void StartListner(IPAddress sourceIp, IPAddress multicastGroupIp, IPAddress localIp, int port)
{
Task.Run(() =>
{
try
{
Console.WriteLine("Starting: " + sourceIp + " - " + multicastGroupIp + " - " + localIp + " / " + port);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint localEndpoint = new IPEndPoint(localIp, port);
socket.Bind(localEndpoint);
byte[] membershipAddresses = new byte[12]; // 3 IPs * 4 bytes (IPv4)
Buffer.BlockCopy(multicastGroupIp.GetAddressBytes(), 0, membershipAddresses, 0, 4);
Buffer.BlockCopy(sourceIp.GetAddressBytes(), 0, membershipAddresses, 4, 4);
Buffer.BlockCopy(localIp.GetAddressBytes(), 0, membershipAddresses, 8, 4);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddSourceMembership, membershipAddresses);
while (true)
{
byte[] b = new byte[1024];
int length = socket.Receive(b);
Console.WriteLine("PORT: " + port + " : " + Encoding.ASCII.GetString(b, 0, length));
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
});
}

Categories

Resources