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")
Related
So, I'm trying to make a chat application where when you are able to select what IP address you want to connect to. These IP addresses are stored in a database and for whatever reason when I extract the IP from a database the program doesn't connect to it, whereas when I directly give the IP in the serverIP variable as: serverIP = "127.0.0.1"; it works. I have no issues extracting the IP from the database, the problem is that when you try to connect to the server with the extracted IP it fails.
This is the code I used to use to connect to a server using an IP from the database:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Address WHERE ID = 1;", conn); //query
OleDbDataReader cusReader = cmd.ExecuteReader();
while (cusReader.Read())
{
ip = cusReader.GetValue(0).ToString();
}
serverIP = ip;
cusReader.Close();
TcpClient client = new TcpClient(serverIP, port);
If you want the ip column, then specify it in the SQL statement:
SELECT ip FROM Address WHERE ID = 1;
or explicitly look up the column by name when you read the results. I'm not sure a while loop is appropriate if you are expecting at most one row.
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;
}
}
I'm trying to get my client app to connect to a server on a remote machine operating on my local network without knowing the server's IP Address to begin with.
Ideally I'd like the client to connect automatically, but since I've been having trouble getting that to work properly, I thought for now I'd have the user manually input their server's IP Address into the client.
I've saved the inputted IP address to a file and loaded it into a string:
string ServerIP = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + #"/ServerIP.cfg");
but I'm not sure how to set that string as the IPEndPoint:
private IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("Insert ServerIP string here"), 8888);
I've unsuccessfully tried using ipString, IPAddress.Parse(ServerIP, 8888);, IPAddress.Parse(string ServerIP, 8888); and multiple other combinations, I still can't figure out the proper syntax for this method, and my Google-fu has failed me on this one.
EDIT: With this implementation I don't get any errors until I try to debug, and I get:
"An unhandled exception of type 'System.ArgumentNullException' occurred in System.dll
Additional information: Value cannot be null." on Client.Connect(serverEndPoint);
private IPEndPoint serverEndPoint;
private TcpClient Client = new TcpClient();
public Client()
{
InitializeComponent();
Client.Connect(serverEndPoint);
string ServerIP = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + #"/ServerIP.cfg");
serverEndPoint = new IPEndPoint(IPAddress.Parse(ServerIP), 8888);
}
IPAddress.Parse only takes one argument, I believe you meant to put the port in the IPEndPoint constructor and not the Parse method.
private IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(ServerIP), 8888);
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.
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;
}
}