Send/receive file over LAN with C# to/from Python - c#

I'm pretty new to Python development and need some help.
I have a Raspberry Pi B+, and I'm planning on using it as a controller for household things (such as turning on a pool pump at a set time). I am pretty familiar with C# and was wondering if there was a way I could write a C# user interface to run on a laptop and send data in the form of a XML file to the Raspberry Pi over a LAN to tell the Pi what to do. I have written some code in C# and some code in Python to try to send and receive a file, but so far my tests have been unsuccessful.
I have some rudimentary code written in Python on the Raspberry Pi for controlling some GPIO pins and was wondering if a connection like this is even feasible of if I should rewrite my Python code into C# also.
Here is my C# send file function
public void SendFile(string fileName)
{
try
{
string IpAddressString = piIP;
IPEndPoint ipEnd_client = new IPEndPoint(IPAddress.Parse(IpAddressString), portnumber);
Socket clientSock_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
string filePath = "";
fileName = fileName.Replace("\\", "/");
Console.WriteLine(fileName);
while (fileName.IndexOf("/") > -1)
{
filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
fileName = fileName.Substring(fileName.IndexOf("/") + 1);
}
byte[] fileNameByte = Encoding.UTF8.GetBytes(fileName);
if (fileNameByte.Length > 5000 * 1024)
{
Console.WriteLine("File size is more than 5Mb, please try with small file.");
return;
}
Console.WriteLine("Buffering ...");
string fullPath = filePath + fileName;
byte[] fileData = File.ReadAllBytes(fullPath);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
Console.WriteLine("Connection to server...");
clientSock_client.Connect(ipEnd_client);
Console.WriteLine("File sending...");
clientSock_client.Send(clientData, 0, clientData.Length, 0);
Console.WriteLine("Disconnecting...");
clientSock_client.Close();
Console.WriteLine("File [" + fullPath + "] transferred.");
}
catch (Exception ex)
{
if (ex.Message == "No connection could be made because the target machine actively refused it")
Console.WriteLine("File Sending fail. Because server not running.");
else
Console.WriteLine("File Sending fail. " + ex.Message);
return;
}
connected = true;
return;
}
Here is my Python receive file function
import socket
import sys
s = socket.socket()
s.bind((socket.gethostname(), 8080))
s.listen(3)
while True:
#Accept connections from the outside
(clientsocket, address) = s.accept()
print(address)
i = 1
f = open('file_' + str(i) + ".xml", 'wb')
i = i + 1
while True:
l = clientsocket.recv(1024)
while l:
f.write(1)
l.clientsocket.recv(1024)
f.close()
sc.close()
s.close()
Again, so far, I am unable to even set up a connection between the two devices. Should I start over on the Pi and try C# instead of Python? Or am I missing something? I've given both devices a static IP address and hardcoded the IP addresses on both machine for now.
EDIT:
Here is the Console and stacktrace I get from C#:
Buffering ...
Connection to server...
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
File Sending fail. No connection could be made because the target machine actively refused it 10.51.21.199:8080
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
at App1.Stuffs.SendFile(String fileName) in
...Projects\App1\App1\Stuffs.cs:line 308
The thread '<No Name>' (0x1684) has exited with code 0 (0x0).

Try to use
s.bind(('', 8080))
to force the Raspberry Pi to listen on all available interfaces, as the socket.gethostname() might not be the interface you are actually expecting.
UPDATE:
Try this on the Raspberry Pi side:
import socket
import sys
s = socket.socket()
s.bind(('', 8080))
s.listen(3)
i = 0
while True:
#Accept connections from the outside
(clientsocket, address) = s.accept()
print(address)
i = i + 1
with open('file_' + str(i) + ".xml", 'wb') as f:
while True:
l = clientsocket.recv(1024)
if not l:
break
f.write(l)
clientsocket.close()
s.close()

I have two ways of accessing my Raspberry Pi from a Windows PC. The first is after installing Putty connection manager on the PC, where entering the RPi IP address produces a Terminal window on the PC, from where I can execute RPi programs.
The RPi is connected to a Windows Workgroup, mapped as drive T:, in my case. My C programs can use this to create files on the RPi for writing or reading.

Related

C# Client can't parse an ip addres

so I am writing a C# client, where the user needs to type which IPv4 address to listen to an incoming connection from. However, though the program compliles, when typing any ip address, it comes back saying the IP was invalid. This is for any IP typed. I am wondering how to correctly parse the IP address typed in to RecieveIP.Text so it will read correctly? Thanks.
try
{
InitializeComponent();
string listenporttext = listenPort.ToString();
IPAddress RIP = IPAddress.Parse(RecieveIP.Text);
client = new Client(RIP, listenporttext);
Console.WriteLine("Recieving information from lead computer " + RIP + " on port: " + listenPort);
recv = client.Receive(data);
string recc1 = recv.ToString();
string data_recieved = recc1;
Console.WriteLine("Recieved Command " + data_recieved);
if (data_recieved == "g")

Pinging an IP and port with C# [duplicate]

I have to check remote IP and Port is available or not.If its is available it will move to next form.If not available it should come to the initial state.I tried using this
while (true)
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
-------
-------
-------
}
I am showing the example coding.it was checking local IP and port and moving to next form.it will check local port and IP is available.if port and IP not available it will come to the initial stage and it was working fine.same thing i have to check in remote Port and IP.
Use the Ping class of .NET to find out if the system is up and connected, the use the PortScanner to check if the port is open. check these links for further reading and exploring.
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping%28v=vs.110%29.aspx
http://social.msdn.microsoft.com/Forums/vstudio/en-US/8e4410bd-307f-4264-9575-cd9882653945/help-with-portscanner-in-c?forum=csharpgeneral
OR
public static bool PingHost(string hostUri, int portNumber)
{
try
{
using (var client = new TcpClient(hostUri, portNumber))
return true;
}
catch (SocketException ex)
{
MessageBox.Show("Error pinging host:'" + hostUri + ":" + portNumber.ToString() + "'");
return false;
}
}

How to check remote IP and Port is available?

I have to check remote IP and Port is available or not.If its is available it will move to next form.If not available it should come to the initial state.I tried using this
while (true)
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
-------
-------
-------
}
I am showing the example coding.it was checking local IP and port and moving to next form.it will check local port and IP is available.if port and IP not available it will come to the initial stage and it was working fine.same thing i have to check in remote Port and IP.
Use the Ping class of .NET to find out if the system is up and connected, the use the PortScanner to check if the port is open. check these links for further reading and exploring.
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping%28v=vs.110%29.aspx
http://social.msdn.microsoft.com/Forums/vstudio/en-US/8e4410bd-307f-4264-9575-cd9882653945/help-with-portscanner-in-c?forum=csharpgeneral
OR
public static bool PingHost(string hostUri, int portNumber)
{
try
{
using (var client = new TcpClient(hostUri, portNumber))
return true;
}
catch (SocketException ex)
{
MessageBox.Show("Error pinging host:'" + hostUri + ":" + portNumber.ToString() + "'");
return false;
}
}

C# Listenin 5060 Port [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Listening to Port 5060
I am developing a SIP client.And I have a question.
I want listen 5060 port for catch the SIP Server Message.For this,I coding something.(Also I take admin rights in program)
But I get SocketException: "An attempt was made to access a socket in a way forbidden by its access permissions" (Native error code: 10013)...
My Code:
private void ListenPort() {
WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);
TcpListener server = null;
Int32 port = 5060;
IPAddress localAddr = IPAddress.Parse("192.168.1.33");
server = new TcpListener(localAddr, port);
Byte[] bytes = new Byte[1000];
String data = null;
while (hasAdministrativeRight == true)
{
server.Start();
int i = 0;
while (1==1)
{
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
data = null;
i = stream.Read(bytes, 0, bytes.Length);
data += System.Text.Encoding.ASCII.GetString(bytes, 0, i);
label3.Text += data;
this.Refresh();
Thread.Sleep(500);
}
}
}
Where do you think the problem?
Have you checked that no other program is already using port 5060? That's what this error can mean.
See this discussion on the matter: http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/d23d471c-002a-4958-829e-eb221c8a4b76/
You need to call server.Start() outside the while loop and before the first AcceptTcpClient call.
Also try using IPAddress.Any instead of IPAddress.Parse("192.168.1.33") for your listener ip
Make sure any other SIP Server program not installed as a Windows service which has using according port.
Type in netstat -an and it will show you the “listening” ports or try to googling port check softwares.
And check your SIP Server configuration for is it running over TCP or UDP.

How can i get a file from remote machine?

How can i get a file from remote computer? i know remote computer ip and 51124 port is open. i need this algorith:(this is a Windows Application visual studio 2008)
1) Connect 192.xxx.x.xxx ip via 51124 port
2) filename:123456 (i want to search it on remote machine)
3) Get File
4) Save C:\
51124 port is open. can i access and can i search any file according to filename?
My code is below:
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 51124);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(maxConnections);
Socket serverSocket = sock.Accept();
byte[] data = new byte[bufferSize];
int received = serverSocket.Receive(data);
int filenameLength = BitConverter.ToInt32(data, 0);
string filename = Encoding.ASCII.GetString(data, 4, filenameLength);
BinaryWriter bWrite = new BinaryWriter(File.Open(outPath + filename, FileMode.Create));
bWrite.Write(data, filenameLength + 4, received - filenameLength - 4);
int received2 = serverSocket.Receive(data);
while (received2 > 0) {
bWrite.Write(data, 0, received2);
received2 = serverSocket.Receive(data);
}
bWrite.Close();
serverSocket.Close();
sock.Close();
MyQuery(targetip, port, filename) i can use it like that: MyQuery(192.xxx.x.xxx,51124,"MyNeddedFile");
MyQuery(targetip, port, filename)
{
.....
...
..
.
}
You have been trying to ask this question a few times now - perhaps this explains why we cannot answer your question:
If you have an FTP server, it will (by default) listen on port 21. So if I send a message according to the FTP protocol to port 21, it will respond.
If I have apache or IIS (or some other webserver) listening on for instance port 80, and I send an FTP message to it, it will give me an error, because they are expecting HTTP requests.
Without knowing what application is listening on port 51124, we can't possibly tell you how to talk to it.

Categories

Resources