First of all sry about my english. My problem is i have electronic circuit on press machine. This circuit sending data to my server without a problem. After i recieve data i need to send command to circuit. In LAN its working like a charm. But out of lan circuit dont recieving my command somehow. Any idea how i can send to udp pocked to machine behind NAT ? my code is bellow , ty for any help.
private void ReceiveMessage()
{
while (true)
{
try
{
var remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
var content = _udpClient.Receive(ref remoteIpEndPoint);
if (content.Length > 0)
{
var message = Encoding.ASCII.GetString(content);
var smsg = message.Split('|');
var pin1 = int.Parse(smsg[13]);
var pin2 = int.Parse(smsg[14]);
var isChanged = CheckChanges(smsg[1]);
if (isChanged == 1)
{
**var recvpt = new IPEndPoint(remoteIpEndPoint.Address, remoteIpEndPoint.Port);
var client = new UdpClient();
var cmd1 = "CP1S" + _pin1Time + "F";
var cmd2 = "CP2S" + _pin2Time + "F";
var senddata1 = Encoding.UTF8.GetBytes(cmd1);
var senddata2 = Encoding.UTF8.GetBytes(cmd2);
client.Send(senddata1, senddata1.Length, recvpt);
client.Send(senddata2, senddata2.Length, recvpt);
client.Close();**
// UpdateChanges(smsg[1]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToStrin<wbr ></wbr>g());
}
}
}
}
Computers that are behind a NAT router are not directly accessible from a remote network. There would need to be rules put in place on your firewall/router to route this traffic to the remote machine. For explicit directions see your WAN/LAN admin. If you don't have one you could try asking over on Server Fault with more information about your network.
Related
I can't connect to wifi networks that the PC doesn't know. If I manually connect first, then the program is able to connect programmatically as long as I don't click on "Forget".
If the network is not known then the ap.Connect(authRequest) returns null.
How can I connect to a wifi network programmatically that the pc doesn't know yet?
var accessPoints = wifi.GetAccessPoints();
List<string> accessPointNames = new List<string>();
foreach (AccessPoint ap in accessPoints)
{
accessPointNames.Add(ap.Name);
string fSSID = "test1234";
if (ap.Name == fSSID)
{
AuthRequest authRequest = new AuthRequest(ap)
{
Password = "12345678"
};
if (ap.Connect(authRequest))
Console.WriteLine("connected");
else
Console.WriteLine("disconnected");
break;
}
}
I would like to connect to multiple TCP/IP devices simultaneously to read or send data by creating N number of sockets to connect to N number of IP addresses. I had written the code as below but it will only create one socket to connect to the first IP address instead of creating 3 sockets to connect to 3 IP addresses. Please help. Thanks.
Similar post : How to connect multiple IP addresses with same port number using TCP/IP client?
Socket[] sockets = new Socket[3];
IPAddress[] ipaddress = new IPAddress[3];
string tempIP = "192.168.1.13";
private void StartClient()
{
try
{
for (int i = 0; i < 3; i++)
{
sockets[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
for (int j = 0; j < 3; j++)
{
ipaddress[j] = IPAddress.Parse(tempIP + (j + 3));
remoteEP = new IPEndPoint(ipaddress[j], port);
MessageBox.Show(remoteEP.ToString());
var result = sockets[i].BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), sockets[i]);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
MessageBox.Show(success.ToString());
if (!success && ButtonStartScan.Text == "Connected")
{
Thread.Sleep(10000);
PortDisconnect();
Thread.Sleep(10000);
PortConnect();
throw new Exception("Failed to connect.");
}
connectDone.WaitOne(1);
if (ButtonStartScan.Text == "Disconnected")
{
PortDisconnect();
}
else
{
stopwatch1.Start();
receiveDone.Reset();
Receive(sockets[i]);
bool poll_check = true;
do
{
if (stopwatch1.ElapsedMilliseconds > 10000)
{
stopwatch1.Restart();
string X5 = "X5";
Send_stop(sockets[i], X5);
sendDone.WaitOne(1000);
for (int row = 0; row < DroneList.Rows.Count; row++)
{
TimeSpan timeDiff = DateTime.Now - Convert.ToDateTime(DroneList.Rows[row].Cells["TimeDetected"].Value);
int time = Convert.ToInt32(timeDiff.TotalSeconds);
if (time > dronecounter)
{
DroneList.Rows[row].Cells["Inject"].Style.BackColor = Color.DarkGray;
if (!DroneList.Rows[row].Cells["DroneType"].Value.ToString().Contains("Wifi"))
{
DroneStatus.ImageLayout = DataGridViewImageCellLayout.Zoom;
Image img1 = Image.FromFile(#"D:\Image\no_alert.PNG");
DroneList.Rows[row].Cells["DroneStatus"].Value = img1;
}
SignalStrength.ImageLayout = DataGridViewImageCellLayout.Zoom;
Image img2 = Image.FromFile(#"D:\Image\no_bar.PNG");
DroneList.Rows[row].Cells["SignalStrength"].Value = img2;
if (DroneList.Rows[row].Cells["Inject"].Value.ToString() == "Stop Distract")
{
if (DroneList.Rows[row].Cells["DroneType"].Value.ToString() == "DJI Phantom 3 STD")
{
DroneList.Rows[row].Cells["Inject"].Style.ForeColor = Color.DodgerBlue;
DroneList.Rows[row].Cells["Inject"].Value = "Inject";
string StopString = "S3";
Send_stop(sockets[i], StopString);
sendDone.WaitOne(1000);
}
else
{
DroneList.Rows[row].Cells["Inject"].Style.ForeColor = Color.DodgerBlue;
DroneList.Rows[row].Cells["Inject"].Value = "Distract";
string StopString = "SD";
Send_stop(sockets[i], StopString);
sendDone.WaitOne(1000);
}
}
}
}
if (!sockets[i].Connected)
{
for (int row = 0; row < DroneList.Rows.Count; row++)
{
if (DroneList.Rows[row].DefaultCellStyle.BackColor == Color.DarkGray)
{
}
else
{
if (DroneList.Rows[row].Cells["Inject"].Value.ToString() == "Stop Inject")
{
if (DroneList.Rows[row].Cells["DroneType"].Value.ToString() == "DJI Phantom 3 STD")
{
DroneList.Rows[row].Cells["Inject"].Style.ForeColor = Color.DodgerBlue;
DroneList.Rows[row].Cells["Inject"].Value = "Distract";
string StopString = "S3";
Send_stop(sockets[i], StopString);
sendDone.WaitOne(1000);
}
else
{
DroneList.Rows[row].Cells["Inject"].Style.ForeColor = Color.DodgerBlue;
DroneList.Rows[row].Cells["Inject"].Value = "Distract";
string StopString = "SD";
Send_stop(sockets[i], StopString);
sendDone.WaitOne(1000);
}
}
DroneList.Rows[row].DefaultCellStyle.BackColor = Color.DarkGray;
DroneList.Rows[row].Cells["Inject"].Style.BackColor = Color.DarkGray;
DroneList.Rows[row].Cells["Whitelist"].Style.BackColor = Color.DarkGray;
if (!DroneList.Rows[row].Cells["DroneType"].Value.ToString().Contains("Wifi"))
{
DroneStatus.ImageLayout = DataGridViewImageCellLayout.Zoom;
Image img1 = Image.FromFile(#"D:\Image\no_alert.PNG");
DroneList.Rows[row].Cells["DroneStatus"].Value = img1;
}
SignalStrength.ImageLayout = DataGridViewImageCellLayout.Zoom;
Image img2 = Image.FromFile(#"D:\Image\no_bar.PNG");
DroneList.Rows[row].Cells["SignalStrength"].Value = img2;
}
}
PortDisconnect();
Thread.Sleep(10000);
PortConnect();
Thread.Sleep(10000);
}
}
}
while (poll_check);
receiveDone.WaitOne();
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Just use a individual TCP socket for each connection/device. It doesn't matter that all devices have the same port, as this is only the port used by the remote device. Your pc will randomly choose a port for the outgoing connection, and you can't (and don't want to) do anything about it.
For example, this is what the communication will look like. The outgoing port really doesn't matter at all:
Your PC:4568 --> xxx.xx.xx.100:8000
Your PC:7568 --> xxx.xx.xx.101:8000
xxx.xx.xx.100:8000 --> Your PC:4568
xxx.xx.xx.101:8000 --> Your PC:7568
Edit:
If you have a small, fixed number of devices, you can just use multiple sockets like this:
Socket client1;
Socket client2;
Socket client3;
client1 = new Socket(IPAddress.Parse("xxx.xxx.xxx.100").AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
client2 = new Socket(IPAddress.Parse("xxx.xxx.xxx.100").AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
client3 = new Socket(IPAddress.Parse("xxx.xxx.xxx.100").AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
remoteEP1 = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.100"), port);
remoteEP1 = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.101"), port);
remoteEP1 = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.102"), port);
If you have a bigger number of devices, or the ip addresses change dynamically, it would make sense to create the sockets in a for-loop and write them to an array.
This is a Networking problem first and barely even a Programming one. The network classes do not care if the target is on the same computer, the same switch or the Voyager Probes.
Socket and IP adress are a integral pair. You can not seperate them from each other.
Knowing only the sockete would be like only knowing the House Number, but not the street. And the IP adress would be only knowing the street, but not which of the several thousand housenumbers.
Communication goes from one pair of IP/Socket to another pair of IP/Socket. In many cases the socket number can be implied. HTTP request usally target Port 80 on the target IP adress.
If you are mostly doing receiving work with limited communication, you can share a port for multiple clients. Port 80 does so. But if the communicaiton is more complex, it is customary to only use the public port to innitate talking, then to all the heavy lifting on a port specific for this process that you jsut dynamically aquire.
I'm trying to listen for UDP packets from unknown source. But can't bind on the "unspecified adress" (0.0.0.0 or ::)
I've already tried listening on ::1. But from what i tested that only works for local connections that don't pass the network interface.
public async void AwaitDiscoveryReply()
{
try
{
using (var client = new UdpClient(AddressFamily.InterNetworkV6))
{
client.Connect(IPAddress.IPv6Any,4568);
var result = await client.ReceiveAsync();
Debug.WriteLine("Received DR");
var stateProtocol = StateProtocol.FromBytes(result.Buffer);
var robeatsDevice = new RobeatsDevice
{
Id = stateProtocol.DeviceId,
Name = stateProtocol.DeviceName,
EndPoint = client.Client.RemoteEndPoint,
StateProtocol = stateProtocol
};
OnDiscoveryReply(new DeviceDiscoveryEventArgs {RobeatsDevice = robeatsDevice});
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
This keeps throwing the exception: The requested address is not valid in its context [::]:4568
UDP sockets are connectionless. "Connect" methods on UDP socket implementations, by convention (don't ask me why) establish default endpoints / filter traffic. If you want to receive traffic from any address, you don't need to "connect" at all. Use the constructor with signature UdpClient(Int32, AddressFamily) and delete the Connect() invocation:
public async void AwaitDiscoveryReply()
{
try
{
using (var client = new UdpClient(4568,AddressFamily.InterNetworkV6))
{
var result = await client.ReceiveAsync();
Debug.WriteLine("Received DR");
var stateProtocol = StateProtocol.FromBytes(result.Buffer);
var robeatsDevice = new RobeatsDevice
{
Id = stateProtocol.DeviceId,
Name = stateProtocol.DeviceName,
EndPoint = client.Client.RemoteEndPoint,
StateProtocol = stateProtocol
};
OnDiscoveryReply(new DeviceDiscoveryEventArgs {RobeatsDevice = robeatsDevice});
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
I found this C# code for simple IP net scanner which scans the connected hosts in the network and displays its physical address and IP address.It works well but only when connected with the network via WIFI. It doesn't work when connected through the network via wires.
[DllImport("iphlpapi.dll", ExactSpelling = true)]
At first, iphlpapi.dll has been imported. So, can you explain it? the rest of the code is given below.
// Use Your work Group WinNT://&&&&(Work Group Name)
DirectoryEntry DomainEntry = new DirectoryEntry("WinNT://" + this.TxtWorkGroup.Text.Trim());
DomainEntry.Children.SchemaFilter.Add("computer");
// To Get all the System names And Display with the Ip Address
foreach (DirectoryEntry machine in DomainEntry.Children)
{
string[] Ipaddr = new string[3];
Ipaddr[0] = machine.Name;
System.Net.IPHostEntry Tempaddr = null;
try
{
Tempaddr = (System.Net.IPHostEntry)Dns.GetHostByName(machine.Name);
}
catch (Exception)
{
MessageBox.Show("Unable to connect with the system :" + machine.Name);
continue;
}
IPAddress[] TempAd = Tempaddr.AddressList;
foreach (IPAddress TempA in TempAd)
{
Ipaddr[1] = TempA.ToString();
byte[] ab = new byte[6];
int len = ab.Length;
// This Function Used to Get The Physical Address
int r = SendARP((int)TempA.Address, 0, ab, ref len);
string mac = BitConverter.ToString(ab, 0, 6);
Ipaddr[2] = mac;
}
ListViewItem TempItem = new ListViewItem(Ipaddr);
this.ListHostIP.Items.Add(TempItem);
}
}
Turn off the WIFI adapter and try it again.
I want to communicate between iPhone and C# server through Sockets,
When I try to create socket from iPhone to my C Sharp server over a LAN using cocoaasynsockets, but it does not create any socket on my server. I tried giving different IPs like 127.0.0.1/192.168.2.102(local)/IP found on (whatispmyip.com), but no gain,
here is my testing code for iPhone
- (IBAction)connect:(id)sender{
GCDAsyncSocket *socket;
socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *err = nil;
if (![socket connectToHost:#"192.168.2.102" onPort:52523 error:&err]) // Asynchronous!
{
NSLog(#error : %#"", err);
}
}
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(#"connected");
}
and here is my c sharp server code
TcpListener _tcpListerner;
public void startingServer() {
// IPAddress ipad = Dns.Resolve("localhost").AddressList[0];
IPAddress ipad = IPAddress.Parse("192.168.2.102");
_tcpListerner = new TcpListener(ipad, 52523);
_tcpListerner.Start();
Console.WriteLine("The local End point is :" +_tcpListerner.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
Thread thread = new Thread(acceptClients);
thread.Start();
}
void acceptClients()
{
Socket s = _tcpListerner.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
char cc = ' ';
string test = null;
Console.WriteLine("Recieved...");
for (int i = 0; i < k - 1; i++)
{
Console.Write(Convert.ToChar(b[i]));
cc = Convert.ToChar(b[i]);
test += cc.ToString();
}
What I am missing in it, what IP should I give, or there is some settings on server side or on iphone(client side) to accept/create socket from network
Use IPAddress.Any on the server to listen on all machine addresses.
On the client side use the LAN address of the server you want to connect to.