I have a computer connected to two readers through TCP/IP, using UDP protocol.
My code looks like this:
IPEndPoint Info = new IPEndPoint(IPAddress.Any, MVM.readerProperties.AutoPort);
EpcSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
EpcSocket.Bind(Info);
IsConnected = true;
EpcSocket.BeginReceive(Epcrecebuffer, 0, Epcrecebuffer.Length, SocketFlags.None, new AsyncCallback(EpcReceiveCallBack), null);
My question is how can I find what IPAdress teh sender has? I need that in my Async function Epcreceivecallback? When using this code the LocalEndpoint is said to be 0.0.0.0
When using one reader I have no issue then I know it's from that one. But when I have two I would like to know from which one the data comes.
Related
I'm trying to write a TCP server in .NETMF 4.3 for my FEZ Spider kit.
public partial class Program
{
void ProgramStarted()
{
ethernetJ11D.NetworkInterface.Open();
ethernetJ11D.UseStaticIP("192.168.0.8", "255.255.255.0", "192.168.0.1");
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
EndPoint endPoint = new IPEndPoint(IPAddress.Any, 7777);
serverSocket.Bind(endPoint);
serverSocket.Listen(10);
new Thread(() =>
{
while (true)
{
Debug.Print("Network up: " + ethernetJ11D.IsNetworkUp);//true
Debug.Print("Network connected: " + ethernetJ11D.IsNetworkConnected);//true
System.Net.Sockets.Socket clientSocket = serverSocket.Accept();//exception!
new Thread(new Request(clientSocket).Process);
}
}).Start();
}
The serverSocket.Accept method throws a SocketException with error code 10050. This page says it's WSAENETDOWN: Network is down. However the ethernetJ11D's properties state that the connection is up and I can ping the device without any problems. What am I doing wrong?
EDIT
When I tried running the following client I got the same exception on the socket.Connect call.
ethernetJ11D.NetworkInterface.Open();
ethernetJ11D.UseStaticIP("192.168.0.8", "255.255.255.0", "192.168.0.1");
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("192.168.0.5"), 7777);
socket.Connect(endpoint);
Debug.Print("connected");
byte[] msg = new byte[] { 7, 77, 222 };
socket.Send(msg);
EDIT 2
I've tried to implement the UDP client instead. It doesn't work either.
I've solved the problem:
Change IPAddress.Any to a static IP,e.g. IPAddress.Parse("192.168.0.8").
Delay Bind by adding Thread.Sleep(3000) right before it. It seems that the interface's network settings configuration takes some time.
I've been making a sample program wherein the user can broadcast messages using sockets and UDP connection. It was successful in LAN but I can't broadcast my messages to other networks (e.g. 10.15.1.11's message to 10.11.1.23). Here's my sample code:
Listener:
bworker = sender as BackgroundWorker;
Socket _ListenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint _ListenerEndPoint = new IPEndPoint(IPAddress.Any, _port);
_ListenerSocket.EnableBroadcast = true;
_ListenerSocket.Bind(_ListenerEndPoint);
//_ListenerSocket.Connect(MulticastIP, _port);
_ListenerSocket.Ttl = 255;
_ListenerSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(MulticastIP));
while (true)
{
byte[] msg = new byte[1024];
_ListenerSocket.Receive(msg);
string StringData = Encoding.Unicode.GetString(msg);
bworker.ReportProgress(0, StringData);
}
Sender:
Socket _ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_ClientSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(MulticastIP));
_ClientSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, int.Parse(ttl));
IPEndPoint _ClientEndPoint = new IPEndPoint(MulticastIP, _port);
_ClientSocket.Connect(_ClientEndPoint);
byte[] MsgByte = new byte[1024];
MsgByte = Encoding.Unicode.GetBytes(txtmsg.Text);
_ClientSocket.Send(MsgByte);
Variables:
public const int _port = 8041;
public const string ttl = "255";
public IPAddress MulticastIP = IPAddress.Parse("239.0.0.222");
Thanks.
The router between you and the other LAN probably refuses to forward packets with multicast destination IPs. To handle multicast properly, the router itself has to be multicast-aware and implement protocols such as PIM (for coordinating multicast between routers) and IGMP (for coordinating multicast with end-hosts)
Your router probably doesn't forward multicast packages. In order for multicast to work all routers along the path of communication must me multicast enabled. Ping only requires the router to forward ping packages so that will really only tell you if you can reach the other computer at all. Take a look at this article to learn more about multicasting in C#.
I am having trouble with sockets connecting from an external source
See below my constructor.
//Using UDP sockets
clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
EndPoint ourEP = new IPEndPoint(IPAddress.Any, 1450);
//Listen asynchronously on port 1450 for coming messages (Invite, Bye, etc).
clientSocket.Bind(ourEP);
//Receive data from any IP.
EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));
byteData = new byte[1024];
//Receive data asynchornously.
clientSocket.BeginReceiveFrom(byteData,
0, byteData.Length,
SocketFlags.None,
ref remoteEP,
new AsyncCallback(OnReceive),
null);
this is connect button function:
private void btnCall_Click(object sender, EventArgs e)
{
//Get the IP we want to connect.
otherPartyIP = new IPEndPoint(IPAddress.Parse(txtCallToIP.Text), 1450);
otherPartyEP = (EndPoint)otherPartyIP;
}
I make chat application peer to peer over internet. i opened port 1450 firewall and add port forward but it's not connecting. Please can you help?
When working with UDP you must ensure that the amount of HOPS a packet can travel is set correctly.
I'm not all to sure but I think the default is either 0 or 1.
Use the Ttl property on your socket to experiment with this. Try setting it to 10, if you are testing on a very short path.
Alternatively set it higher byt take care as the ttl property for datagrams denote the amount of points/routers (actually hops) the packet can travel trhough to reach its destination.
The value range can be from 0 to 255.
Hope this helps
I wanted to send UdpPacket to a specific remote host (I already know the public IP and Port).
I wanted to use C#'s UdpClient class.
static int Main()
{
UdpClient client = new UdpClient();
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("1.2.3.4"), 9999);
byte[] data = GetData();
client.Send(data, data.Length, remoteEP);
}
When sending a packet, the UdpClient choose an available port automatically. I want to manually set the port, from which I send the packets.
Thanks for your help in advance!
Try specifying the endpoint when you create the UdpClient:
UdpClient client = new UdpClient(localEndpoint);
EDIT: Note that you can also specify just the port number:
UdpClient client = new UdpClient(localPort);
That may be somewhat simpler :)
I am trying to get an ip address that is bound to receiveSock. How can i get it.
Ques 1:
ipEndReceive = new IPEndPoint(IPAddress.Any, receivePort);
receiveSock = new Socket(AddressFamily.InterNetwork
, SocketType.Stream, ProtocolType.Tcp);
receiveSock.Bind(ipEndReceive);
When code reaches Bind function. An error occurs
Invalid Argument, Error Code: 10022,
Message : An invalid argument was
supplied
Ques 2:
ipEndReceive = new IPEndPoint(IPAddress.Parse("127.0.0.1"), receivePort);
receiveSock = new Socket(AddressFamily.InterNetwork
, SocketType.Stream, ProtocolType.Tcp);
receiveSock.Bind(ipEndReceive);
ErrorLog.WritetoErrorlog("\nRemote IP Address : " + ((IPEndPoint)receiveSock.RemoteEndPoint).Address.ToString()
When I tries with this Ip. It shows me the same error as above
First, it looks like it's the local end point you want. Secondly when you specify IPAddress.Any (0.0.0.0) you explicitly state that the Socket is to be bound to no particular interface. Each IP adress matches exactly one interface.
var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(new IPEndPoint(IPAddress.Any, somePort));
Trace.WriteLine(s.LocalEndPoint); // should be what you're looking for
The socket is bound and will be used for receiving connections. It doesn't have a RemoteEndPoint. This should be abundantly clear becuase the Accept method returns a new Socket object that represents the connection between two end points (local/remote).
Note: that this is an IPv4 socket (AddressFamily.InterNetwork) so don't try and bind it to anything else.
Check out the docs on MSDN, you can learn more about typical Winsock programming (as the Socket class is just a Winsock wrapper) there.