I have a program that sends a message to a server and the server recognizes the message inteprets it and sends back the message to the port it was listening from in the begining. so let's say the client sends from port 5000. The server will read the message from port 5000, and send back a message to the port the client used to send the message so the client can receive it. My question now is that I don't want to fix a port for the server ( i don't want the server to always send back to client to port 1000), so how can i know what port my client used to send the message every single time? So in my client, my UdpClient Listener = new UdpClient(xxx) [(xxxx) being the port number] can be filled by a new value every single time? the value of the port it used to send the message
thanks
here's my program :
private const int sendPort = 9999;
static void Main(string[] args)
{
Boolean done = false;
IPAddress send_to_address = IPAddress.Parse("xx.xxx.xxx.xxx");
IPEndPoint sending_end_point = new IPEndPoint(send_to_address, sendPort);
IPEndPoint receiving_end_point = new IPEndPoint(IPAddress.Any, 0);
UdpClient Listener = new UdpClient(WHAT TO PUT HERE???);
while (!done)
{
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Console.WriteLine("Enter text to send");
string text_to_send = Console.ReadLine();
// the socket object must have an array of bytes to send.
// this loads the string entered by the user into an array of bytes.
byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
// Remind the user of where this is going.
Console.WriteLine("sending to address: {0} port: {1}", sending_end_point.Address, sending_end_point.Port);
sending_socket.SendTo(send_buffer, sending_end_point);
Console.WriteLine("Message has been sent to the broadcast address");
Console.WriteLine("Now we are waiting for a message back from the Listener");
// here we receive the Message from the Server
Byte[] ByteFromListener = Listener.Receive(ref receiving_end_point);
string datafromreceiver = Encoding.ASCII.GetString(ByteFromListener);
Console.WriteLine(Datafrom receiver)
}
}
}
}
The answer was quite simple. Just needed to use the same socket to receive the message.
Here is the code :
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class Program
{
private const int sendPort = 9999;
static void Main(string[] args)
{
Boolean done = false;
IPAddress send_to_address = IPAddress.Parse("10.128.105.177");
IPEndPoint sending_end_point = new IPEndPoint(send_to_address, sendPort);
EndPoint receiving_end_point = new IPEndPoint(IPAddress.Any, 0);
while (!done)
{
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Console.WriteLine("Enter text to send");
string text_to_send = Console.ReadLine();
// the socket object must have an array of bytes to send.
// this loads the string entered by the user into an array of bytes.
byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
// Remind the user of where this is going.
Console.WriteLine("sending to address: {0} port: {1}", sending_end_point.Address, sending_end_point.Port);
sending_socket.SendTo(send_buffer, sending_end_point);
Console.WriteLine("Message has been sent to the broadcast address");
Console.WriteLine("Now we are waiting for a message back from the Listener");
Byte[] ByteFromListener = new byte[8000];
sending_socket.ReceiveFrom(ByteFromListener, ref receiving_end_point);
string datafromreceiver;
datafromreceiver = Encoding.ASCII.GetString(ByteFromListener).TrimEnd('\0');
//Here we print the message from the server
Console.WriteLine(datafromreceiver.ToString());
}
}
}
}
Related
So I am coding a C# UDP server client, which I am wanting for it to listen for incoming connections on port 8001 and then send a message in return. The problem it tries to send the message first and as such sends to to IP address 0.0.0.0 using IPAdress.ANY. How can I recode this to listen for incoming UDP connections first then send message once connection is found? Thanks.
while (!done)
{
string text_to_send = satt.Text;
if (text_to_send.Length == 0)
{
done = true;
}
else
{
//Encode the attack command, and send on the port to the listening computers.
byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
Console.WriteLine("Sending the attack information to the IP: {0} port: {1}",
sending_end_point.Address,
sending_end_point.Port);
const int listenPort = 8001;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
string data_recieved;
byte[] recieve_byte_array;
recieve_byte_array = listener.Receive(ref groupEP);
data_recieved = Encoding.ASCII.GetString(recieve_byte_array, 0, recieve_byte_array.Length);
Console.WriteLine("Number of searches by the listening computers: " + data_recieved);
I'm sending socket with this function:
public static List<Socket> samp = new List<Socket>();
IPHostEntry host = null;
Socket sock;
host = Dns.GetHostEntry(serverip);
foreach (IPAddress address in host.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, 7777);
sock = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(ipe);
if (sock.Connected)
{
samp.Add(sock);
}
}
samp.Add(sock); sends my ip, for example 127.0.0.1, how can I add string to ip? For example: Nickname:127.0.0.1 ? Thanks in advance! Or how can I send two sockets? For example:
First socket - nickname
Second - ip
Thnx alot
I am not able to receive back my own packets send on multicast. i created two Udpclient receiver is to receive packets on multicast group and sender is to send packets. my packets are send to the group but i cannot receive back the packets send by me....
public void Join()
{
IPAddress ip1 = IPAddress.Any;
localep = new IPEndPoint(ip1, port);
Receiver = new UdpClient();
Receiver.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Receiver.Client.Bind(localep);
Sender = new UdpClient();
Sender.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Sender.Client.Bind(localep);
IPAddress ip = IPAddress.Parse(IP);
remoteep = new IPEndPoint(ip, port);
Sender.JoinMulticastGroup(ip);
Sender.EnableBroadcast = true;
Sender.MulticastLoopback = true;
Receiver.JoinMulticastGroup(ip);
Receiver.EnableBroadcast = true;
Receiver.MulticastLoopback = true;
udpState.ipEndpt = RemoteIpEndPoint;
udpState.udpClient = Receiver;
Receiver.BeginReceive(new AsyncCallback(GetMsg), udpState);
}
void GetMsg(IAsyncResult ar)
{
UdpClient udpClient = (UdpClient)((UdpState)(ar.AsyncState)).udpClient;
IPEndPoint ipEndpt = (IPEndPoint)((UdpState)(ar.AsyncState)).ipEndpt;
RecByte = Receiver.EndReceive(ar, ref ipEndpt);
}
//Sending packets logic
McastOTS.Sender.Send(sendBytes, sendBytes.Length, McastOTS.remoteep);
Seems to me all you need to do is call BeginReceive again after your EndReceive. Otherwise, you'll only get 1 message and won't see any others...
void GetMsg(IAsyncResult ar)
{
UdpClient udpClient = (UdpClient)((UdpState)(ar.AsyncState)).udpClient;
IPEndPoint ipEndpt = (IPEndPoint)((UdpState)(ar.AsyncState)).ipEndpt;
RecByte = Receiver.EndReceive(ar, ref ipEndpt);
Receiver.BeginReceive(GetMsg, udpState);
}
I am making a client that connect to a server that is locally hosted that gets stock numbers from the server. The program does work if i use this code below but the way it works is by getting the dns name so in theory it only takes www.website.com and I cant figure out how I can get it to recognize a normal ip of 127.0.0.1 or localhost IP:
IPHostEntry ipHostInfo = Dns.GetHostEntry("www.website.com");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
Attached is my attemp to get this to resolve the ip but I dont think I am approaching this right the full code can be seen here:StockReader Client Code
public class AsynchronousClient
{
private const int port = 21;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
// The response from the remote device.
private static String response = String.Empty;
private static void StartClient()
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
//******************ISSUE BEGINS HERE*********************************
string sHostName = Dns.GetHostName();
IPHostEntry ipHostInfo = Dns.GetHostEntry(sHostName);
IPAddress [] ipAddress = ipHostInfo.AddressList;
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
Send(client, "This is a test<EOF>");
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Response received : {0}", response);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
When you set the value of ipAddress, you can use the IPAddress.Parse method to pass in a string and retrieve an IPAddress object instead of using the domain name:
string ip = "127.0.0.1";
IPAddress address = IPAddress.Parse(ipAddress);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
Try using string sHostName = "localhost";
// Establish the remote endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, portnumber);
// Create a TCP/IP socket.
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(remoteEP);
How can I programmatically determine if I have access to a server (TCP) with a given IP address and port using C#?
You could use the Ping class (.NET 2.0 and above)
Ping x = new Ping();
PingReply reply = x.Send(IPAddress.Parse("127.0.0.1"));
if(reply.Status == IPStatus.Success)
Console.WriteLine("Address is accessible");
You might want to use the asynchronous methods in a production system to allow cancelling, etc.
Assuming you mean through a TCP socket:
IPAddress IP;
if(IPAddress.TryParse("127.0.0.1",out IP)){
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(IPs[0], port);
}
catch(Exception ex){
// something went wrong
}
}
For more information: http://msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4
Declare string address and int port and you are ready to connect through the TcpClient class.
System.Net.Sockets.TcpClient client = new TcpClient();
try
{
client.Connect(address, port);
Console.WriteLine("Connection open, host active");
} catch (SocketException ex)
{
Console.WriteLine("Connection could not be established due to: \n" + ex.Message);
}
finally
{
client.Close();
}
This should do it
bool ssl;
ssl = false;
int maxWaitMillisec;
maxWaitMillisec = 20000;
int port = 555;
success = socket.Connect("Your ip address",port,ssl,maxWaitMillisec);
if (success != true) {
MessageBox.Show(socket.LastErrorText);
return;
}