I receive unexpected udp packets when i run the code in windows(both client and server in same system). My client is written in c# and the server is in python.
When i run in the same code in mac i don't have any problem and i receive expected messages(here i opened a port in mac for udp).
client(c#):
public static void Main(string[] args)
{
Console.WriteLine("Receiver");
// This constructor arbitrarily assigns the local port number.
UdpClient udpClient = new UdpClient();
//udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, 137));
try
{
//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 137);
string message ;
do
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
message = Encoding.ASCII.GetString(receiveBytes);
// Uses the IPEndPoint object to determine which of these two hosts responded.
Console.WriteLine("This is the message you received: " +
message);
//Console.WriteLine("This message was sent from " +
// RemoteIpEndPoint.Address.ToString() +
// " on their port number " +
// RemoteIpEndPoint.Port.ToString());
}
while (message != "exit");
udpClient.Close();
//udpClientB.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("Press Any Key to Continue");
Console.ReadKey();
}
server(python-3.6):
import socket
from time import sleep
rx=0 #000
ry=0 #000
rz=0 #000
e=0 #000
UDP_IP = "172.20.10.4"
UDP_PORT = 137
MESSAGE = ""
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
while(1):
if (rx<360):
rx=rx+1
if ((ry<360) & (rx>=360)):
ry=ry+1
if ((rx>=360) & (ry>=360)):
rx=0
ry=0
if (rz<360):
rz=rz+1
if (rz>=360):
rz = 0
if (e<10):
e=e+1
if(e>=10):
e=0
#verify rx
if (rx<10):
rxs='00'+str(rx)
if ((rx>=10) & (rx<100)):
rxs='0'+str(rx)
if (rx>=100):
rxs=str(rx)
#verify ry
if (ry<10):
rys='00'+str(ry)
if ((ry>=10) & (ry<100)):
rys='0'+str(ry)
if (ry>=100):
rys=str(ry)
#verify rz
if (rz<10):
rzs='00'+str(rz)
if ((rz>=10) & (rx<100)):
rzs='0'+str(rz)
if (rz>=100):
rzs=str(rz)
#verify e
if (e<10):
es='00'+str(e)
if ((e>=10) & (e<100)):
es='0'+str(e)
if (e>=100):
es=str(e)
MESSAGE = 'h'+'01'+'rx'+rxs+'ry'+rys+'rz'+rzs+'e'+es
#sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))
sleep(0.1)
Expected message(i receive the below in mac):
This is the message you received: h01rx360ry151rz009e007
I receive the below in windows:
This is the message you received: ?{ EJFDEBFEEBFACACACACACACACACACAAA
Can someone please letme know where i went wrong with.
thanks in advance
If the udp packets are not associated with your server this might be helpful: https://forum.fortinet.com/tm.aspx?m=106656 and here: https://superuser.com/questions/637696/what-is-netbios-does-windows-need-its-ports-137-and-138-open
Windows is using port 137 for its own services. Try change your port on the Windows device.
Looks like you are having issues with port selection. The packets you see are from Windows.
You don't need the bind statement. This is a working example I'm using with .net core
internal class Program
{
private const int PORT = 5678;
private static void Main(string[] args)
{
Console.WriteLine("Packet Forwarding UP!");
var client = new UdpClient(PORT);
// can use IPAddress.Any or other IP depending on where they are coming from.
var ipEndPoint = new IPEndPoint(IPAddress.Loopback, PORT);
while (true)
{
Console.Write("Waiting... ");
var receive = client.Receive(ref ipEndPoint);
Console.WriteLine(" - Received Data - " + receive.Length);
}
}
}
I've been testing the client with PacketSender's Intense Traffic Generator and confirming traffic with NirSoft TcpUdpWatch
Related
I am trying to read location data coming from a Airlink MP70 GNSS Gateway into a mock up console app. The GNSS sentences are sent to my computer through ethernet and UDP.
Gateway IP: 192.168.13.31 (GNSS receiver)
Source Port: 17335
Destination IP: 192.168.13.100
Port: 12351
I can see the UDP datagrams with wireshark. The highlighted area is the GNSS data I am trying to extract.
How would I go receiving this data into a basic console app preferably c# but c++/java python ok too.
Here is what I have so far but I am not seeing any output (it is just the basic code for a UDP client on Microsoft c# site).
private const int listenPort = 12351;
public static void Main()
{
UdpClient receivingUdpClient = new UdpClient(listenPort);
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
My bad - was firewall blocking connection. Thanks from those who helped
The task of the code is to find the servers that answers the #SERVER question. If I enter the server's IP address works fine, but not at 192.168.1.255 adress.
Thanks for the help!
My code is here:
static void Main(string[] args)
{
Console.WriteLine(IPAddress.IPv6Any);
UdpClient udpClient = new UdpClient();
try
{
udpClient.EnableBroadcast = true;
udpClient.Connect("192.168.1.255",80);
// Sends a message to the host to which you have connected.
Byte[] sendBytes = Encoding.ASCII.GetBytes("#SERVER");
udpClient.Send(sendBytes, sendBytes.Length);
//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
// Uses the IPEndPoint object to determine which of these two hosts responded.
Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
udpClient.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadKey();
}
'''
192.168.1.255or better ANY IP address ending with 255 is a broadcast address.
Messages sent to this IP are not targeted specifically but will (in the most cases) be broadcasted to all devices in your network (exceptions might be up to your local configuration). If the devices in your network react to broadcast messages or not depends on their configuratation. However sending a discovery message to the brodcast-address as you do, does not make much sense as it is not allowed to assign this IP address to any device.
I am trying to figure out how to receive UDP packets that are being broadcast out by a set of devices. I can see them coming in using Wireshark, but cant figure out how to receive them in my application. The packets are being broadcast out to all devices on the network on the same port. I need to be able to receive them from any IP address sending them. I also have 2 NIC cards if it makes a difference. I only need to listen on 1, but I'm not sure if I have to specify that. I have tried some various things with the UdpClient, but have had no luck.
192.168.1.20 255.255.255.255 UDP 768 Source port: 3001 Destination port: 3002
bool done = false;
UdpClient listener = new UdpClient(3001);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 3002);
string received_data;
byte[] receive_byte_array;
try
{
while (!done)
{
Debug.WriteLine("Waiting for broadcast");
receive_byte_array = listener.Receive(ref groupEP);
Debug.WriteLine("Received a broadcast from {0}", groupEP.ToString() );
received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
Debug.WriteLine("data follows \n{0}\n\n", received_data);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
listener.Close();
Im new to Sockets and C# in general and am having a difficult time implementing a simple upd listener function. I've spent alot of time searching the web tying unsuccessfully to intergate any of the numerious examples online. So any suggestions, links, examples would be greatly appreciated!
At this point, I have a third party application broadcasting over port 6600 a general UPD message containing information about the location of the application server (ServerName, IP Address, etc.). I'd like to design my listener client application to capture the UPD broadcast and generate a collection of the available servers which can be used to future processing.
The problem I'm having is that when I attempt to create the listener using listener.Listen(0) if fails and generates a general type error. If I attempt to us the UdpClient class my application hangs and never returns any data. The Code for both examples is listed below:
namespace UDPListener
{
class Program
{
static void Main(string[] args)
{
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
listener.Bind(new IPEndPoint(IPAddress.Any, 6600));
listener.Listen(6);
Socket socket = listener.Accept();
Stream netStream = new NetworkStream(socket);
StreamReader reader = new StreamReader(netStream);
string result = reader.ReadToEnd();
Console.WriteLine(result);
socket.Close();
listener.Close();
}
}
}
And the UdpClient:
private void IdentifyServer()
{
//Creates a UdpClient for reading incoming data.
UdpClient receivingUdpClient = new UdpClient(6600);
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Output.Text = ("This is the message you received " +
returnData.ToString());
Output.Text = ("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
dtb was absolutely write! After much research and some help from a friend I realized that what I was actually looking for was a solution for Multicasting. I'll include the links below.
#dtb, thanks for helping point me in the right direction!
http://www.codeproject.com/Articles/1705/IP-Multicasting-in-C
http://codeidol.com/csharp/csharp-network/IP-Multicasting/Csharp-IP-Multicast-Support/
I'm going to setup a small client/server server in TCP/IP mode, I use VS2010,C# to develop my apps, I've googled a lot and could find some source codes, but none of them work in internet, I can get some answers in my own local system, i.e. I run my server, then listen for my own localhost (127.0.0.1) then send some data (for example using telnet), it works fine but when I do the same over internet I get nothing! I want to use port 80, as I want to send/receive http data, I have tested several source codes, here is the last code I have used (and it works on localhost with telnet)
//server code:
form_load()
IPAddress localAddress = IPAddress.Parse("127.0.0.1");
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndpoint = new IPEndPoint(localAddress, 80);
// Bind the socket to the end point
listenSocket.Bind(ipEndpoint);
// Start listening, only allow 1 connection to queue at the same time
listenSocket.Listen(1);
listenSocket.BeginAccept(new AsyncCallback(ReceiveCallback), listenSocket);
Console.WriteLine("Server is waiting on socket {0}", listenSocket.LocalEndPoint);
// Start being important while the world rotates
while (true)
{
Console.WriteLine("Busy Waiting....");
Thread.Sleep(2000);
}
public static void ReceiveCallback(IAsyncResult AsyncCall)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
Byte[] message = encoding.GetBytes("I am a little busy, come back later!");
Socket listener = (Socket)AsyncCall.AsyncState;
Socket client = listener.EndAccept(AsyncCall);
Console.WriteLine("Received Connection from {0}", client.RemoteEndPoint);
client.Send(message);
Console.WriteLine("Ending the connection");
client.Close();
listener.BeginAccept(new AsyncCallback(ReceiveCallback), listener);
}
send data (client), of course I haven't used this code, is it right?
public static string SendData()
{
TcpClient client = new TcpClient();
client.Connect(IP, 80);
StreamWriter sw = new StreamWriter(client.GetStream());
StreamReader sr = new StreamReader(client.GetStream());
//if statement evalutes to see if the user has selected to update the server
//" " = update server
//"" = do not update the server
//if (updateData.Equals(""))
//{
// space = "";
//}
//else if (!updateData.Equals(""))
//{
// space = " ";
//}
//Refrences stream writer, username variable passed in from GUI
//space variable provides update function: "" = dont update. " " = update database.
sw.WriteLine("h");
sw.Flush();
//data send back from the server assigned to string variable
//string recieved = sr.ReadLine();
return "";
}
I'm going to have the server code in my Server (winserver 2008R2) but currently test it in normal PCs, what am I doing wrong? I want to send some http packet from a random system (with a random IP) to my server (which I know its IP), what should I do? is it possible with tcp/ip or I should do something else?
is it related to static IP? should I certainly have static IP? my web server has a static IP but my clients do not, is it a problem?
I think I have some problem in defining ports and IPs, how should I set them? my server has a specific IP, but I don't know IP of my clients, would you please explain it to me step by step?
thanks
The two most common problems in this scenario:
Ensure your server's router is using port forwarding to forward HTTP requests from the router to the server.
Ensure you are connecting to the server's public IP address, not its local network address.