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.
Related
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.
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'm trying to write a program for a computer with 2 network adapters (Private and Public) that echoes data received on Private to Public and vice versa. I only need it to listen on two specific ports, and more specifically, it should open a socket server on Private and a socket client on Public.
The computer's IP address on Public is 192.168.1.21 and its IP address on Private is 172.16.13.1, so I thought something like this would work:
IPEndPoint privateEndpoint1 = new IPEndPoint(IPAddress.Parse("172.16.13.1"), port1);
IPEndPoint privateEndpoint2 = new IPEndPoint(IPAddress.Parse("172.16.13.1"), port2);
IPEndPoint publicEndpoint1 = new IPEndPoint(IPAddress.Parse("192.168.1.21"), port1);
IPEndPoint publicEndpoint2 = new IPEndPoint(IPAddress.Parse("192.168.1.21"), port2);
TcpListener priList1 = new TcpListener(privateEndpoint1);
TcpListener priList2 = new TcpListener(privateEndpoint2);
TcpClient pubCli1 = new TcpClient(publicEndpoint1); //Error here
TcpClient pubCli2 = new TcpClient(publicEndpoint2);
I then get the streams and do the actual echoing.
The problem is that I get an error on the line that I marked:
Only one usage of each socket address (protocol/network address/port) is normally permitted
It seems from the error that the IPEndPoint constructor is not differentiating between the two IP addresses and the two network adapters. I've looked into using normal Sockets instead of TcpClients, but that didn't seem to change anything.
I have a multi-homed machine and need to answer this question:
Given an IP address of the remote machine, which local interface is appropriate to use for communication.
This needs to be done in C#. I can do this query using Win32 Socket and SIO_ROUTING_INTERFACE_QUERY but looking around in the .net framework documentation I haven't found an equivalent for it.
Someone was nice enough to writez the code, see https://searchcode.com/codesearch/view/7464800/
private static IPEndPoint QueryRoutingInterface(
Socket socket,
IPEndPoint remoteEndPoint)
{
SocketAddress address = remoteEndPoint.Serialize();
byte[] remoteAddrBytes = new byte[address.Size];
for (int i = 0; i < address.Size; i++) {
remoteAddrBytes[i] = address[i];
}
byte[] outBytes = new byte[remoteAddrBytes.Length];
socket.IOControl(
IOControlCode.RoutingInterfaceQuery,
remoteAddrBytes,
outBytes);
for (int i = 0; i < address.Size; i++) {
address[i] = outBytes[i];
}
EndPoint ep = remoteEndPoint.Create(address);
return (IPEndPoint)ep;
}
which is used like (example!):
IPAddress remoteIp = IPAddress.Parse("192.168.1.55");
IpEndPoint remoteEndPoint = new IPEndPoint(remoteIp, 0);
Socket socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
IPEndPoint localEndPoint = QueryRoutingInterface(socket, remoteEndPoint );
Console.WriteLine("Local EndPoint is: {0}", localEndPoint);
Please note that although one is specifying an IpEndPoint with a Port, the port is irrelevant. Also, the returned IpEndPoint.Port is always 0.
I didn't know about this, so just had a look in the Visual Studio Object browser, and it looks like you can do this from the System.Net.Sockets namespace.
In that namespace is a Socket class which contains a method IOControl. One of the overloads for this method takes an IOControlCode (enum in the same namespace) which contains an entry for `RoutingInterfaceQuery'.
I'll try and put some code together as an example now.
I need to determine the IP of a machine that has sent me a multicast packet, so that I can respond to it via unicast.
I'm using the following csharp (.Net 3.5) code to receive the packets over a multicast connection (code has been edited for brevity, with error checking and irrelevant options removed):
IPEndPoint LocalHostIPEnd = new IPEndPoint(IPAddress.Any, 8623);
Socket UDPSocket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
UDPSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, 1);
UDPSocket.Bind(LocalHostIPEnd);
//Join the multicast group
UDPSocket.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse("225.2.2.6")));
IPEndPoint LocalIPEndPoint = new IPEndPoint(IPAddress.Any ,Target_Port);
EndPoint LocalEndPoint = (EndPoint)LocalIPEndPoint;
// Create the state object.
StateObject state = new StateObject();
state.buffer.Initialize();
state.workSocket = UDPSocket;
state.id = "state0";
//Set up my callback
UDPSocket.BeginReceiveMessageFrom(
state.buffer,
0,
StateObject.BufferSize,
0,
ref LocalEndPoint,
new AsyncCallback(ReceiveCallback),
state);
And here's the callback, where I'm trying to get the source IP:
private void ReceiveCallback( IAsyncResult ar )
{
IPEndPoint LocalIPEndPoint = new IPEndPoint(IPAddress.Any, Target_Port);
EndPoint LocalEndPoint = (EndPoint)LocalIPEndPoint;
// Read data from the remote device.
// The following code attempts to determine the IP of the sender,
// but instead gets the IP of the multicast group.
SocketFlags sFlags = new SocketFlags();
IPPacketInformation ipInf = new IPPacketInformation();
int bytesRead = client.EndReceiveMessageFrom(ar, ref sFlags,
ref LocalEndPoint, out ipInf);
log.Warn("Got address: " + ipInf.Address.ToString());
}
I know the correct source IP is in the IP header, since I can clearly see it there when I sniff the packet in wireshark. However, instead of printing out the IP of the sending system (192.168.3.4), the above code prints out the IP of the multicast group that I am subscribed to (225.2.2.6). Is there a way to get the source IP instead?
Isn't your answer in the LocalEndPoint variable, which is the EndPoint of the packet's source, i.e., the dude on the other end. Note that I would probably rename this variable something like "remoteEP", and initialize it to something non-specific to avoid confusion.